How to Write Simple XML Documents with ElementTree in Python
Create well-structured XML documents in memory using Python's built-in ElementTree module, complete with nested elements, attributes, and text content.
Python code
26 linesimport xml.etree.ElementTree as ET
def create_xml_document():
# Create root element
root = ET.Element("catalog")
# Create a book element with attributes and children
book1 = ET.SubElement(root, "book", id="bk101")
ET.SubElement(book1, "author").text = "Gambardella, Matthew"
ET.SubElement(book1, "title").text = "XML Developer's Guide"
ET.SubElement(book1, "price").text = "44.95"
# Create a second book
book2 = ET.SubElement(root, "book", id="bk102")
ET.SubElement(book2, "author").text = "Ralls, Kim"
ET.SubElement(book2, "title").text = "Midnight Rain"
ET.SubElement(book2, "price").text = "5.95"
return root
if __name__ == "__main__":
root = create_xml_document()
# Convert to bytes and pretty-print with indentation
ET.indent(root, space=" ")
xml_string = ET.tostring(root, encoding="unicode")
print(xml_string)
Output
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
</book>
</catalog>
How it works
ET.Element creates the root element, while ET.SubElement adds a child and returns it for further nesting. Attributes are passed as keyword arguments (like id="bk101") in the SubElement call, and text content is set via the .text attribute on the element. ET.indent(root, space=" ") adds two-space indentation to make the output human-readable. ET.tostring with encoding="unicode" converts the element tree to a single string format that can be printed or saved to a file. The entire process builds the document in memory without touching the filesystem, which is ideal for generating XML on the fly in web applications or APIs.
Common mistakes
- Using ET.Element instead of ET.SubElement for children, which creates orphaned elements not attached to the root.
- Forgetting to set the .text attribute, resulting in empty or incomplete XML elements.
- Not calling ET.indent, which outputs a one-line XML string that is difficult to read or debug.
- Using encoding="utf-8" instead of "unicode" when you need a Python string rather than bytes.
Variations
- Write the XML to a file directly with tree = ET.ElementTree(root); tree.write("catalog.xml", xml_declaration=True, encoding="utf-8")
- Use ET.fromstring to parse an existing XML string, then modify and re-serialize it instead of building from scratch.
Real-world use cases
- Generating XML responses for legacy SOAP or REST APIs that expect XML over JSON payloads.
- Creating configuration files (like Ant build scripts or Maven POMs) for automated build processes.
- Exporting structured data from a Python application into XML format for interoperability with other enterprise systems.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.