Search⌘ K

How to Create XML with ElementTree

Explore how to create XML documents with Python's ElementTree. Understand how to build XML structures programmatically, add elements and subelements, set values, and save them to files for data processing or storage.

We'll cover the following...

Creating XML with ElementTree is very simple. In this section, we will attempt to create the XML above with Python. Here’s the code:

Python 3.5
import xml.etree.ElementTree as xml
def createXML(filename):
"""
Create an example XML file
"""
root = xml.Element("zAppointments")
appt = xml.Element("appointment")
root.append(appt)
# add appointment children
begin = xml.SubElement(appt, "begin")
begin.text = "1181251680"
uid = xml.SubElement(appt, "uid")
uid.text = "040000008200E000"
alarmTime = xml.SubElement(appt, "alarmTime")
alarmTime.text = "1181572063"
state = xml.SubElement(appt, "state")
location = xml.SubElement(appt, "location")
duration = xml.SubElement(appt, "duration")
duration.text = "1800"
subject = xml.SubElement(appt, "subject")
tree = xml.ElementTree(root)
with open(filename, "w") as fh:
tree.write(fh)
if __name__ == "__main__":
createXML("appt.xml")

If you run this code, you should get ...