import xml.dom.minidom

dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
Answer from Ben Noland on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
January 12, 2026 - XML (Extensible Markup Language) is a standard format for storing and exchanging data. It is both human-readable and machine-readable. Let’s look at two libraries used for XML parsing in Python.
Discussions

Logging to XML file
Hello :wave:! I’d like to write data coming from a socket (after some processing) to an file in XML format. This should be rotated each day and x days should be kept in a given directory. The structure of that XML is p… More on discuss.python.org
🌐 discuss.python.org
0
0
February 25, 2023
Creating a simple XML file using python - Stack Overflow
What are my options if I want to create a simple XML file in python? (library wise) The xml I want looks like: some value1 ... More on stackoverflow.com
🌐 stackoverflow.com
Proper indentation for XML files
I'm not sure if there is one correct way to add indentation to the XML files, but it works. You can use that before saving the XML files. If there are some other features you'd want to use in XML file handling but are not present in the built in xml APIs of Python, you can use lxml, a third party module. More on reddit.com
🌐 r/PythonLearning
1
4
April 8, 2025
How to process / parse XML with Python
Best bet: Use lxml . There's a nice tutorial on the site, too . You can also use the built-in XML parser, either with ElementTree (common) or XML DOM (rarer) , or any other related library from the xml module , but most people prefer lxml, as it's much more powerful (and in parts, compatible with ElementTree). More on reddit.com
🌐 r/learnpython
5
11
October 22, 2017
🌐
Python Forum
python-forum.io › thread-23494.html
Preserve xml file format
Hi! I would like to manipulate an xml file yet preserve it's format (extra spaces, comments, cr, ..). lxml preserve comments out of the box but was unable to figure out the rest. My current solution is to parser the file line by line.. For example:
🌐
GeeksforGeeks
geeksforgeeks.org › python › pretty-printing-xml-in-python
Pretty Printing XML in Python - GeeksforGeeks
July 23, 2025 - In this method, we will be using the python lxml module. This library converts the original XML file to a more beautiful XML file.
🌐
LearnPython.com
learnpython.com › blog › read-xml-into-python
How to Read XML Files into Python | LearnPython.com
In this article, you’ll learn what an XML file is, what they are used for, and how to read XML into Python using a few different libraries. The ability to extract information from various file formats is a crucial data analysis skill. This is no different with an XML file: XML is a common ...
🌐
TutorialsPoint
tutorialspoint.com › pretty-printing-xml-in-python
Pretty Printing XML in Python
July 25, 2023 - In cocnclusion, Pretty printing XML in Python is essential for improving the readability and structure of XML data. Whether using the xml.dom.minidom or xml.etree.ElementTree library, developers can easily format XML with proper indentation.
🌐
Dive into Python
diveintopython.org › home › learn python programming › file handling and file operations › xml files handling
XML File Operations with Python - Read, Write and Parse XML Data
May 3, 2024 - In both examples, the ElementTree() class is used to create an XML element tree. The write() method is then used to write the element tree to an XML file. By specifying encoding and xml_declaration in the second example, a custom-formatted XML file is created with an XML declaration at the top.
Find elsewhere
🌐
Python.org
discuss.python.org › python help
Logging to XML file - Python Help - Discussions on Python.org
February 25, 2023 - # simulate incoming data new_data = '<Telegram Timestamp="2021-01-25T07:47:47.0888991Z" Service="L_Data.ind" FrameFormat="CommonEmi" RawData="2900BCD01151295103008007B7" />' # ------------------------- xml_close = "</CommunicationLog>\n" line_read = "" log_data = [] xml_file = "log.xml" # create a generator for the file read log_file = (line for line in open(xml_file, mode='r', encoding='UTF-8')) xml_open = next(log_file).strip() while line_read != xml_close: line_read = next(log_file) if line_read and line_read != xml_close: log_data.append(line_read.strip()) log_data.append(new_data) with open(xml_file, mode='w', encoding='UTF-8') as f: print(xml_open, file=f) for item in log_data: print(f" {item}", file=f) print(xml_close.strip(), file=f) ... TimedRotatingFileHandler looks like the right basis (with your own format).
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'))
🌐
Real Python
realpython.com › ref › stdlib › xml
xml | Python Standard Library – Real Python
>>> import xml.etree.ElementTree as ET >>> root = ET.fromstring("<data><item>Python</item></data>") >>> root.tag 'data' Parses XML documents from strings, file, and other data sources · Supports both SAX and DOM parsing models · Allows creation and modification of XML documents · Provides an API through ElementTree for common XML tasks · Handles Unicode and namespaces in XML documents · Supports reading and writing XML in both compact and pretty-printed formats ·
🌐
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.
🌐
Scraping Robot
scrapingrobot.com › blog › create-xml-with-python
Create XML With Python: A Roadmap to Parsing With Python
February 24, 2024 - BeautifulSoup is an excellent choice to create XML with Python if you’re dealing with irregularly formatted XML documents, especially if they’re “broken” or have malformations. While BeautifulSoup is widely recognized for HTML parsing, its flexible parsing capabilities also extend to handling XML.
🌐
DataCamp
datacamp.com › tutorial › python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - Check for common issues like malformed XML, unsupported encodings, or incorrect file paths. Use Python's error handling mechanisms (try-except blocks) to diagnose and manage parsing errors gracefully. ElementTree does not support pretty-printing directly, but you can use xml.dom.minidom to parse the XML string and then use its toprettyxml() method to format the XML for readability.
🌐
Medium
mjamilmoughal.medium.com › working-with-xml-using-python-933e39598581
Working with XML using Python. In this article we are going to learn… | by Jamil Moughal | Medium
April 17, 2021 - In this article we are going to learn how to parse, explore, modify and populate an XML file using Python ElementTree. We will understand what is XML file and its data format, why it is used and how to explore its tree structure.
🌐
Apify
blog.apify.com › python-parse-xml
How to parse XML in Python
July 16, 2025 - Since we’ve created an XML file with some book data, we’ll use the parse() function to parse the XML data. However, we’ll also show you how to use the fromstring() function to parse XML data stored in a string format.
🌐
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. ... While JSON may be the go-to format for many web APIs, XML has distinct advantages in certain use cases.
🌐
Reddit
reddit.com › r/pythonlearning › proper indentation for xml files
r/PythonLearning on Reddit: Proper indentation for XML files
April 8, 2025 -

I'm working on a Python script that reads data from an Excel file and generates individual XML files based on each valid row. The script extracts various fields, handles date formatting, and builds a structured XML tree for each record. For certain entries, I also include duplicate tags with additional details (e.g., a second <Description> tag with a formatted date).

Now, I want the XML output to be properly indented for readability. I came across xml.etree.ElementTree.indent(tree, space=' ', level=0) as a possible way to format the XML. Is this the correct and recommended method to add indentation to the XML files I'm creating? If so, where exactly in my code should I use it for best results? Also im pretty new to python, like this would be my first time doing something on python apart from v basic code in the past. If anyone knows some resources that they think could help, i would really appreciate that too. Any help is appreciated :)

🌐
Codeblogmoney
codeblogmoney.com › xml-pretty-print-using-python-with-examples
XML Pretty Print using Python – with Examples
May 30, 2018 - Python and XML both are treading in programming fields. Python generates dynamic XML string and received by the client. To save memory or bandwidth it’s better to send the minified version ...
🌐
Martiandefense
book.martiandefense.llc › notes › coding-programming › python › xml-basics-with-python
XML Basics with Python | Martian Defense NoteBook
This example creates a root 'root' element, then creates a 'book' subelement with a 'category' attribute, and a 'title' subelement with a text value. Finally, it writes the XML document to a file. ... This code does the same thing, but with the added benefit of the pretty_print option, which formats the XML with indentation for easier reading.