I simply solved it with the indent() function:

xml.etree.ElementTree.indent(tree, space=" ", level=0) Appends whitespace to the subtree to indent the tree visually. This can be used to generate pretty-printed XML output. tree can be an Element or ElementTree. space is the whitespace string that will be inserted for each indentation level, two space characters by default. For indenting partial subtrees inside of an already indented tree, pass the initial indentation level as level.

tree = ET.ElementTree(root)
ET.indent(tree, space="\t", level=0)
tree.write(file_name, encoding="utf-8")

Note, the indent() function was added in Python 3.9.

Answer from Rafal.Py on Stack Overflow
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - xml.etree.ElementTree.indent(tree, space=' ', level=0)¶ · Appends whitespace to the subtree to indent the tree visually. This can be used to generate pretty-printed XML output. tree can be an Element or ElementTree. space is the whitespace ...
🌐
TutorialsPoint
tutorialspoint.com › pretty-printing-xml-in-python
Pretty Printing XML in Python
July 25, 2023 - Define the `pretty_print_xml_elementtree` function: This function takes an XML string as input and is responsible for parsing and pretty printing the XML using `xml.etree.ElementTree`.
🌐
my tiny TechBlog
norwied.wordpress.com › 2013 › 08 › 27 › 307
Pretty print XML trees in python – my tiny TechBlog
June 1, 2018 - from xml.etree import ElementTree as ET ''' copy and paste from http://effbot.org/zone/element-lib.htm#prettyprint it basically walks your tree and adds spaces and newlines so the tree is printed in a nice way ''' def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i ''' function to build an example
🌐
GitHub
gist.github.com › 6375a1cccd39fe9f2dd7
ElementTree pretty · GitHub
ElementTree pretty · Raw · ElementTree_pretty.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Python
bugs.python.org › issue23847
Issue 23847: Add xml pretty print option to ElementTree - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/68035
🌐
lxml
lxml.de › tutorial.html
The lxml.etree Tutorial
One of the important differences is that the ElementTree class serialises as a complete document, as opposed to a single Element. This includes top-level processing instructions and comments, as well as a DOCTYPE and other DTD content in the document: >>> prettyprint(tree) # lxml 1.3.4 and later <!DOCTYPE root PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "file://local.dtd" [ <!ENTITY tasty "parsnips"> ]> <root> <a>parsnips</a> </root>
🌐
GeeksforGeeks
geeksforgeeks.org › python › pretty-printing-xml-in-python
Pretty Printing XML in Python - GeeksforGeeks
July 23, 2025 - Python3 · from lxml import etree temp = etree.parse("gfg.xml") new_xml = etree.tostring(temp, pretty_print = True, encoding = str) print(new_xml) Output: <gfg> <instructor> <Name>Sandeep Jain Sir</Name> </instructor> </gfg> Comment · Article Tags: Article Tags: Technical Scripter ·
Find elsewhere
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
from xml.etree import ElementTree from xml.dom import minidom def prettify(elem): """Return a pretty-printed XML string for the Element.
🌐
DataCamp
datacamp.com › tutorial › python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - 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.
🌐
CopyProgramming
copyprogramming.com › howto › how-do-i-get-python-s-elementtree-to-pretty-print-to-an-xml-file
Python: Tips for Formatting XML Output with Python's ElementTree?
April 16, 2023 - Techniques for Formatting XML Output from Python's ElementTree, ElementTree Pretty-Printing in Python Using XML, Enhancing the Readability of XML ElementTree with Indentation
🌐
DNMTechs
dnmtechs.com › how-to-achieve-pretty-printing-in-xml-files-using-pythons-elementtree
How to Achieve Pretty Printing in XML Files Using Python’s ElementTree – DNMTechs – Sharing and Storing Technology Knowledge
Pretty printing XML files is essential for improving readability and making it easier to work with XML data. Python’s ElementTree library provides built-in methods for achieving pretty printing, such as the indent() function. Additionally, libraries like lxml offer more advanced options for ...
🌐
GitHub
gist.github.com › akaihola › 7659310
XML pretty-print for ElementTree · GitHub
October 27, 2020 - XML pretty-print for ElementTree. GitHub Gist: instantly share code, notes, and snippets.
🌐
Python
bugs.python.org › issue17372
Issue 17372: provide pretty printer for xml.etree.ElementTree - Python tracker
March 7, 2013 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/61574
🌐
Python
mail.python.org › pipermail › tutor › 2010-August › 077999.html
[Tutor] Elementtree and pretty printing in Python 2.7
August 22, 2010 - Sorry wrong import! from xml.minidom import parseString from xml.etree import ElementTree Karim On 08/22/2010 05:24 PM, Karim wrote: > > Hello Jerry, > > Tricky solution using minidom (standard) Not tested: > > import ElementTree > import minidom > > def prettyPrint(element): > txt = ElementTree.tostring(element) > print minidom.parseString(txt).toprettyxml() > > > Regards > Karim > > On 08/22/2010 04:51 PM, Jerry Hill wrote: >> On Fri, Aug 20, 2010 at 3:49 AM, Knacktus<knacktus at googlemail.com> >> wrote: >>> Hi guys, >>> >>> I'm using Python 2.7 and the ElementTree standard-lib to write some >>> xml.
🌐
Codeblogmoney
codeblogmoney.com › xml-pretty-print-using-python-with-examples
XML Pretty Print using Python – with Examples
May 30, 2018 - Some time for debugging purposes, we need to see beautified XML data to understand and to Debug. This article will help to pretty-print XML data. There are two examples in the post. ... Here is the explanation for the code. ... This is an XML library available in python to convert the DOM object from XML string or from the XML file.