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'))
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-xml-documents-using-python
Create XML Documents using Python - GeeksforGeeks
July 12, 2025 - Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks. After creating a child product the filename is saved as 'any name as per your choice.xml'. Do not forget to append .xml at the end of the filename you have given to the file.
Discussions

How to create XML file using Python? - Stack Overflow
I would like to create an XML file. More on stackoverflow.com
🌐 stackoverflow.com
Python create XML file - Stack Overflow
Even if the above was correct, ... an XML file? I've tried looking at other answers but most of the replies are to generate XML like this: ... And I can't figure out how to generate the kind I need. Sorry if I've made obvious mistakes. I appreciate any help. Thank you! ... class is a Python keyword, you ... More on stackoverflow.com
🌐 stackoverflow.com
Generating XML with Python
I would use xml.etree for this kind of thing. You can generate xml with templates, but there are escaping issues to consider, and you risk generating broken xml. More on reddit.com
🌐 r/learnpython
5
3
March 16, 2016
python - Best way to generate xml? - Stack Overflow
I'm creating an web api and need a good way to very quickly generate some well formatted xml. I cannot find any good way of doing this in python. Note: Some libraries look promising but either lack documentation or only output to files. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - Source code: Lib/xml/etree/ElementTree.py The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Tutorial: This is a short tutorial for using xml....
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
Now available for Python 3! Buy the book! ... In addition to its parsing capabilities, xml.etree.ElementTree also supports creating well-formed XML documents from Element objects constructed in an application. The Element class used when a document is parsed also knows how to generate a serialized form of its contents, which can then be written to a file ...
🌐
TutorialsPoint
tutorialspoint.com › create-xml-documents-using-python
Create XML Documents using Python
In this piece, we will investigate the use of Python in the process of generating XML documents. First, we will look at a simple illustration, and then we will go to more complex illustrations. ... To create an XML document, we will use the ElementTree library provided by Python.
🌐
Scraping Robot
scrapingrobot.com › blog › create-xml-with-python
Create XML With Python: A Roadmap to Parsing With Python
February 24, 2024 - Web scrapers can crawl through sites or APIs to extract data and export it into structured XML files, which you can then parse for actionable insights using Python. ... This guide will walk you through how to create XML with Python using both standard and third-party libraries.
Find elsewhere
🌐
Roy Tutorials
roytuts.com › home › python › building xml using python
Building XML Using Python - Roy Tutorials
November 21, 2023 - Here in the below Python XML builder script I import the required module. Then I define a method that does the task of pretty printing of the XML structure otherwise all will be written in one line and it would a bi difficult to read the XML file. Next I create the root element called bookstore with attribute speciality that has value novel.
🌐
MojoAuth
mojoauth.com › parse-and-generate-formats › parse-and-generate-xml-with-python
Parse and Generate XML with Python | Parse and Generate Formats
You can construct XML documents programmatically in Python using the xml.etree.ElementTree module. This allows you to create new elements, assign attributes, and set text content directly from your Python code.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python
November 30, 2017 - ElementTree is also great for writing data to XML files. The code below shows how to create an XML file with the same structure as the file we used in the previous examples.
Top answer
1 of 1
3

You are on the right track save for a few minor syntax and usage issues:

  1. class is a Python keyword, you can't use it as a function parameter name (which is essentially what class = 'playlistItem' is doing
  2. data-type is not a valid variable name in Python, it will be evaluated as data MINUS type, consider using something like dataType or data_type. There might be ways around this but, IMHO, that would make the code unnecessarily complicated without adding any value (please see Edit #1 on how to do this)

That being said, the following code snippet should give you something usable and you can move on from there. Please feel free to let me know if you need any additional help:

from lxml import etree

data_el = etree.Element('data')

# You can do this in a loop and keep adding new elements
# Note: A deepcopy will be required for subsequent items
li_el = etree.SubElement(data_el, "li", class_name = 'playlistItem', data_type = "local", data_mp3 = "PATH")
a_el = etree.SubElement(li_el, "a", class_name = 'playlistNotSelected', href='#')

print etree.tostring(data_el, encoding='utf-8', xml_declaration = True, pretty_print = True)

This will generate the following output (which you can write to a file):

<?xml version='1.0' encoding='utf-8'?>
<data>
  <li class_name="playlistItem" data_mp3="PATH" data_type="local">
    <a class_name="playlistNotSelected" href="#"/>
  </li>
</data>

Edit #0:

Alternatively, you can also write to a file by converting it to an ElementTree first, e.g.

# Replace sys.stdout with a file object pointing to your object file:
etree.ElementTree(data_el).write(sys.stdout, encoding='utf-8', xml_declaration = True, pretty_print = True)

Edit #1:

Since element attributes are dictionaries, you can use set to specify arbitrary attributes without any restrictions, e.g.

li_el.set('class', 'playlistItem')
li_el.set('data-type', 'local')
🌐
MicroPyramid
micropyramid.com › blog › building-and-parsing-xml-document-using-python
Building and Parsing XML Document using Python | MicroPyramid
For creating element instance, we need to use Element constructor or subelement() To create an element instance factory function. import xml.etree.ElementTree as xml filename = "/home/abc/Desktop/test_xml.xml" root = xml.Element("Users") userelement ...
🌐
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.

🌐
Real Python
realpython.com › ref › stdlib › xml
xml | Python Standard Library – Real Python
The Python xml package provides tools for parsing and creating XML documents that you can use to store and transport structured data. It offers a variety of modules for different XML processing needs, such as DOM, SAX, and ElementTree.
🌐
GeeksforGeeks
geeksforgeeks.org › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
August 10, 2024 - Beautiful Soup supports the HTML parser included in Python’s standard library, but it also supports a number of third-party Python parsers. One is the lxml parser (used for parsing XML/HTML documents). lxml could be installed by running the following command in the command processor of your Operating system: ... Firstly we will learn how to read from an XML file. We would also parse data stored in it. Later we would learn how to create an XML file and write data to it.
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to create xml documents using python
5 Best Ways to Create XML Documents Using Python - Be on the Right Side of Change
February 26, 2024 - This code snippet creates an XML document with a root element “Contacts” and adds a sub-element “Contact” with a child “Name” containing text “John Doe”. It then writes the XML structure to a file named “contacts.xml”. The lxml library is a powerful, feature-rich tool for XML processing in Python.
🌐
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...
🌐
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.
The XML file will be where we store data to be read by Python. In our example, we will be updating the inventory of a store that sells products related to Python, such as hoodies, shirts, caps, and more. Before we do that, we need to create a Python file and import some modules from the standard ...
Starred by 7 users
Forked by 12 users
Languages   Python 100.0% | Python 100.0%