These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5. Deprecated and folded into the regular ElementTree as an automatic thing as of 3.3.)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

  • API docs for the implementation in the Python standard library
  • Introductory Tutorial (From the original author's site)
  • LXML etree tutorial. (With example code for loading the best available option from all major ElementTree implementations)

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.
Answer from ssokolow on Stack Overflow
Top answer
1 of 6
424

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5. Deprecated and folded into the regular ElementTree as an automatic thing as of 3.3.)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

  • API docs for the implementation in the Python standard library
  • Introductory Tutorial (From the original author's site)
  • LXML etree tutorial. (With example code for loading the best available option from all major ElementTree implementations)

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.
2 of 6
79

The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

#!/usr/bin/python
import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
        DOC(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),
            )   
        )   

print lxml.etree.tostring(the_doc, pretty_print=True)

Output:

<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </doc>
</root>

It also supports adding to an already-made node, e.g. after the above you could say

the_doc.append(FIELD2('another value again', name='hithere'))
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ xml.etree.elementtree.html
xml.etree.ElementTree โ€” The ElementTree XML API
Loads an external XML section into this element tree. source is a file name or file object. parser is an optional parser instance. If not given, the standard XMLParser parser is used.
๐ŸŒ
Board Infinity
boardinfinity.com โ€บ blog โ€บ reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python | Board Infinity
August 13, 2025 - Learn to read and write XML files in Python using libraries like ElementTree, with examples to handle data efficiently in structured XML formats.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
January 12, 2026 - from bs4 import BeautifulSoup with open('dict.xml', 'r') as f: data = f.read() bs_data = BeautifulSoup(data, 'xml') for tag in bs_data.find_all('child', {'name':'Frank'}): tag['test'] = "WHAT !!" print(bs_data.prettify()) ... ElementTree is included in Pythonโ€™s standard library, so no installation is required.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ xml โ€บ etree โ€บ ElementTree โ€บ create.html
Creating XML Documents - Python Module of the Week
import sys from xml.etree.ElementTree import Element, SubElement, ElementTree top = Element('top') child = SubElement(top, 'child') child.text = 'This child contains text.' empty_child = SubElement(top, 'empty_child') for method in [ 'xml', 'html', 'text' ]: print method ElementTree(top).write(sys.stdout, method=method) print '\n' Three methods are supported: xml ยท The default method, produces <empty_child />. html ยท Produce the tag pair, as is required in HTML documents (<empty_child></empty_child>). text ยท Prints only the text of nodes, and skips empty tags entirely. $ python ElementTree_write_method.py xml <top><child>This child contains text.</child><empty_child /></top> html <top><child>This child contains text.</child><empty_child></empty_child></top> text This child contains text.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ create-xml-documents-using-python
Create XML Documents using Python - GeeksforGeeks
July 12, 2025 - Python3 ยท from xml.dom import minidom import os root = minidom.Document() xml = root.createElement('root') root.appendChild(xml) productChild = root.createElement('product') productChild.setAttribute('name', 'Geeks for Geeks') xml.appendChild(productChild) xml_str = root.toprettyxml(indent ="\t") save_path_file = "gfg.xml" with open(save_path_file, "w") as f: f.write(xml_str) Output: 2) Creating XML document using ElementTree Firstly we have to import 'xml.etree.ElementTree' for creating a subtree.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ create-xml-documents-using-python
Create XML Documents using Python
The above code creates an XML file called 'person.xml' and writes the XML contents to the file.
Find elsewhere
๐ŸŒ
Zyte
zyte.com โ€บ learn โ€บ a-practical-guide-to-xml-parsing-with-python
A Practical Guide to Python XML Parsing
Python, providing not just basic methods but also advanced techniques like handling XML namespaces, performing XPath queries, and mapping XML data to custom Python objects. By the end, you will have a deep understanding of how to read, modify, and write XML files efficiently using Python.
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ stdlib โ€บ xml
xml | Python Standard Library โ€“ Real Python
>>> import xml.etree.ElementTree as ET >>> root = ET.Element("data") >>> item = ET.SubElement(root, "item") >>> item.text = "Python" >>> tree = ET.ElementTree(root) >>> ET.dump(tree) <data><item>Python</item></data>
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ generating xml with python
r/learnpython on Reddit: Generating XML with Python
March 16, 2016 -

The last few days I've been thinking and searching ways about how to generate XML in a nice way.

I have an XSD which extends the GraphML specification in order to draw more sophisticated diagrams (e.g. UML). The Structure is something like this (I replaced attribute values with python format placeholders)

<xs:Node>
   <xs:Geometry height="{height}" width="{width}" x="{x}" y="{y}"/>
   <xs:Fill color="{color}"/>
   <xs:NodeLabel ...>{node_label}</y:NodeLabel>
</xs:Node>

Current idea/concept

Classes which represent a node and act as a mere data container.

class XMLBase(object):
    def __repr__(self):
        return str(self.__dict__)
    
    def __str__(self):
        return self.xml.format(**self.__dict__)

class Geometry(XMLBase):
    def __init__(self, height=28.0, width=100.0, x=0.0, y=0.0):
        self.xml = '<xs:Geometry height="{height}" width="{width}" x="{x}" y="{y}"/>'
        self.height = height
        self.width = width
        self.x = x
        self.y = y

class Fill(XMLBase):
...

The __str__ method inserts the attributes into the XML string and returns it. The class for the Node would contain an instance of Geometry, Fill, NodeLabel and others, and generate the respective XML representation. The composition of classes is actually the XML data represented by python objects. Other than using classes, one could use lists or dictionaries, but classes seem nicer to use.

A previous idea was to have a big template with placeholders and insert the values with format, but this approach is less flexible and I'd say more difficult to understand (and maintain).

Other ideas were to store the XML templates in variables and let functions generate the correct XML structure.

Now I'd like to know your thoughts about these approaches, different approaches, or maybe someone knows best practices.

๐ŸŒ
Stack Abuse
stackabuse.com โ€บ reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python
November 30, 2017 - You may also notice that writing XML data in this way (calling tree.write with a file name) adds some more formatting to the XML tree so it contains newlines and indentation.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - 5. Efficient Parsing with iterparse (Python 3.10): Optimized for memory efficiency, particularly useful when working with large XML files. 6. Expanded documentation (Ongoing updates): The Python documentation for ElementTree is now more comprehensive, including best practices and advanced use cases. 1. write() with xml_declaration in Python 3.8+: The write() method's xml_declaration parameter is deprecated when the encoding is set to 'unicode'.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ xml.dom.minidom.html
xml.dom.minidom โ€” Minimal DOM implementation
Write XML to the writer object. The writer receives texts but not bytes as input, it should have a write() method which matches that of the file object interface. The indent parameter is the indentation of the current node.
๐ŸŒ
Scraping Robot
scrapingrobot.com โ€บ blog โ€บ create-xml-with-python
Create XML With Python: A Roadmap to Parsing With Python
February 24, 2024 - Pull parsers combine elements of both DOM and SAX to create XML with Python. They provide an API that allows the application to pull, or request, the next event from the parser. They let a program ask for pieces of an XML document one by one, whenever itโ€™s ready to handle them.
๐ŸŒ
Luisartola
luisartola.com โ€บ easy-xml-in-python
Easy XML in Python
xml.etree.ElementTree is a very nice module because it provides classes that let you describe XML from Python in a very similar way to what you would do when writting raw XML by hand.
๐ŸŒ
MojoAuth
mojoauth.com โ€บ parse-and-generate-formats โ€บ parse-and-generate-xml-with-python
Parse and Generate XML with Python | Parse and Generate Formats
Working with XML data in Python can quickly become tedious if you're manually parsing strings or building complex structures. This guide shows you how to leverage Python's built-in libraries to effortlessly read and create XML documents. You'll learn to navigate hierarchical data, extract specific elements, and programmatically generate well-formed XML for your applications.
๐ŸŒ
GitHub
github.com โ€บ WritingPanda โ€บ Python-XML-Tutorial
GitHub - WritingPanda/Python-XML-Tutorial: A tutorial for people who want to learn how to start using Python to read and write XML.
A tutorial for people who want to learn how to start using Python to read and write XML. - WritingPanda/Python-XML-Tutorial
Starred by 7 users
Forked by 12 users
Languages ย  Python 100.0% | Python 100.0%
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-35417.html
how I write the output into xml file in python?
I have an automatically generated j son, I load it in the file (it is a list of dictionaries) and then I convert it to xml but how do I move the output to an 'xml1.xml' file? import json from dicttoxml import dicttoxml with open('json_gen...