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
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding [1] is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file.
Discussions

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 do I get Python's ElementTree to pretty print to an XML file? - Stack Overflow
This code was made in Python3.7, but still works in Python2.7. ... It would be nice if you would not have to indent it manually. ... Bravo! This is dedication! ... This is a good solution for when we don't want to write the XML to a file. – FearlessFuture Commented Sep 28, 2016 at 17:05 ... I get an error when I try this "Couldn't find a tree builder with the features you requested: xml. Do you need to install a parser library?" I have valid XML in string format... More on stackoverflow.com
🌐 stackoverflow.com
June 14, 2019
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
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
People also ask

What is the easiest way to pretty print XML in Python
ANS: For Python 3.9+, xml.etree.ElementTree.indent() is the most straightforward built-in method. For older versions or more advanced control, lxml with etree.tostring(..., pretty_print=True) is highly recommended.
🌐
sqlpey.com
sqlpey.com › python › python-pretty-print-xml
Python: How to Pretty Print XML - sqlpey
What are some alternatives to pretty printing XML in Python
ANS: Besides minidom and ElementTree, popular external libraries like lxml, BeautifulSoupxmltodict, and vkbeautify offer various methods for XML pretty printing, each with its own strengths.
🌐
sqlpey.com
sqlpey.com › python › python-pretty-print-xml
Python: How to Pretty Print XML - sqlpey
How do I handle CDATA sections when pretty printing XML
ANS: When using lxml, ensure you set strip_cdata=False in the XMLParser to preserve CDATA sections during pretty printing.
🌐
sqlpey.com
sqlpey.com › python › python-pretty-print-xml
Python: How to Pretty Print XML - sqlpey
🌐
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.
🌐
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.
🌐
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 ...
🌐
sqlpey
sqlpey.com › python › python-pretty-print-xml
Python: How to Pretty Print XML - sqlpey
November 4, 2025 - import xml.dom.minidom xml_fname = 'your_document.xml' # or xml_string = '<root><item>value</item></root>' # Parse the XML file or string dom = xml.dom.minidom.parse(xml_fname) # Or for a string: dom = xml.dom.minidom.parseString(xml_string) # Generate a pretty-printed XML string pretty_xml_as_string = dom.toprettyxml() print(pretty_xml_as_string) While minidom is readily available, it can sometimes introduce extra blank lines. A common workaround involves filtering these out: import xml.dom.minidom import os def format_xml_string(xml_string): """Formats an XML string and removes excessive new
Find elsewhere
🌐
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.
🌐
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:
🌐
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 :)

🌐
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 ...
🌐
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.
🌐
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.
🌐
Edureka
edureka.co › blog › python-xml-parser-tutorial
Python XML Parser Tutorial | ElementTree and Minidom Parsing | Edureka
December 5, 2024 - Python allows parsing these XML documents using two modules namely, the xml.etree.ElementTree module and Minidom (Minimal DOM Implementation). Parsing means to read information from a file and split it into pieces by identifying parts of that particular XML file. Let’s move on further to see how we can use these modules to parse XML data. This module helps us format XML data in a tree structure which is the most natural representation of hierarchical data.
🌐
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.
🌐
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.
🌐
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 ·
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.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).