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.

Easy Python 3.9+ Aug 9, 2026 Files & data 14 views 0 copies

Python code

26 lines
Python 3.9+
import 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

stdout
<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

  1. Write the XML to a file directly with tree = ET.ElementTree(root); tree.write("catalog.xml", xml_declaration=True, encoding="utf-8")
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.