create xml element in python

To create an XML element in Python you can use the Element class from xml.etree.ElementTree. Here is an example:

main.py
import xml.etree.ElementTree as ET

# create root element
root = ET.Element("users")

# create child element
user = ET.SubElement(root, "user")

# add attribute to the element
user.set("id", "1")

# create sub-elements
name = ET.SubElement(user, "name")
name.text = "John"

age = ET.SubElement(user, "age")
age.text = "30"

# generate XML string
xml_str = ET.tostring(root, encoding="unicode")

# print the XML string
print(xml_str)
433 chars
24 lines

This will generate the following XML output:

<users>
   <user id="1">
      <name>John</name>
      <age>30</age>
   </user>
</users>
89 chars
7 lines

related categories

gistlibby LogSnag