gistlib
To create an XML element in Python you can use the Element class from xml.etree.ElementTree. Here is an example:
Element
xml.etree.ElementTree
main.pyimport 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 chars24 lines
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)
This will generate the following XML output:
<users> <user id="1"> <name>John</name> <age>30</age> </user> </users> 89 chars7 lines
<users> <user id="1"> <name>John</name> <age>30</age> </user> </users>
gistlibby LogSnag