Advertisement
Python253

create_example_xml

Mar 11th, 2024
661
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: create_example_xml.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script creates an example XML file ('example.xml') with sample data.
  10.  
  11. Requirements:
  12. - Python 3.x
  13.  
  14. Usage:
  15. 1. Save this script as 'create_example_xml.py'.
  16. 2. Run the script.
  17.  
  18. Note: Adjust the 'xml_filename' variable in the script as needed.
  19. """
  20.  
  21. import xml.etree.ElementTree as ET
  22.  
  23. def create_example_xml(filename):
  24.     # Create the root element
  25.     root = ET.Element("example_data")
  26.  
  27.     # Create child elements with data
  28.     person1 = ET.SubElement(root, "person")
  29.     ET.SubElement(person1, "name").text = "John Doe"
  30.     ET.SubElement(person1, "age").text = "25"
  31.     ET.SubElement(person1, "city").text = "New York"
  32.  
  33.     person2 = ET.SubElement(root, "person")
  34.     ET.SubElement(person2, "name").text = "Jane Smith"
  35.     ET.SubElement(person2, "age").text = "30"
  36.     ET.SubElement(person2, "city").text = "San Francisco"
  37.  
  38.     person3 = ET.SubElement(root, "person")
  39.     ET.SubElement(person3, "name").text = "Bob Johnson"
  40.     ET.SubElement(person3, "age").text = "22"
  41.     ET.SubElement(person3, "city").text = "Los Angeles"
  42.  
  43.     # Create the ElementTree and write to the XML file
  44.     tree = ET.ElementTree(root)
  45.     tree.write(filename)
  46.  
  47. if __name__ == "__main__":
  48.     # Set the filename for the example XML file
  49.     xml_filename = 'example.xml'
  50.  
  51.     # Create the example XML file in the current working directory
  52.     create_example_xml(xml_filename)
  53.  
  54.     print(f"Example XML file '{xml_filename}' created in the current working directory.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement