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

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
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
what config file format do you prefer?

I use INI files with JSON values and a bit of custom parsing, so that I can load substructures. For example:

Title = "Foo"

[Logging]
StdLog = null
ErrLog.Level = "WARN"

gets parsed into {"Title": "Foo", "Logging": {"StdLog": None, "ErrLog": {"Level": "WARN"}}}.

The configparser module is a bit clunky and.. unpythonic, but usable.

More on reddit.com
🌐 r/Python
27
16
April 3, 2018
🌐
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 ...
🌐
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:
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. ... While JSON may be the go-to format for many web APIs, XML has distinct advantages in certain use cases.
🌐
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 ...
🌐
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.
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
The output contains only the XML nodes in the tree, not the XML declaration with version and encoding. $ python ElementTree_create.py <top><!--Generated for PyMOTW--><child>This child contains text.</ch ild><child_with_tail>This child has regular text.</child_with_tail>A nd "tail" text.<child_with_entity_ref>This &amp; that</child_with_en tity_ref></top>
🌐
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.
🌐
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 - 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.
🌐
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).
🌐
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 ·
🌐
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.
🌐
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 :)