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`.
🌐
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>
🌐
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
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
from xml.etree.ElementTree import Element, SubElement, Comment from ElementTree_pretty import prettify top = Element('top') comment = Comment('Generated for PyMOTW') top.append(comment) child = SubElement(top, 'child') child.text = 'This child contains text.' child_with_tail = SubElement(top, 'child_with_tail') child_with_tail.text = 'This child has regular text.' child_with_tail.tail = 'And "tail" text.' child_with_entity_ref = SubElement(top, 'child_with_entity_ref') child_with_entity_ref.text = 'This & that' print prettify(top) ... $ python ElementTree_create_pretty.py <?xml version="1.0" ?> <top> <!--Generated for PyMOTW--> <child> This child contains text.
🌐
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.
Find elsewhere
🌐
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
🌐
Narkive
tutor.python.narkive.com › HewyHE4O › pretty-printing-xml-using-lxml-on-python3
[Tutor] Pretty printing XML using LXML on Python3
Post by SM $ python3 testx.py b'<root>\n <child/>\n <child>some text</child>\n</root>\n' print() first gets the object as a string. tostring() returns bytes, and bytes.__str__ returns the same as bytes.__repr__. You can decode ... s = etree.tounicode(root, pretty_print=True) print(s) <root> <child/> <child>some text</child> </root>...
🌐
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
In the above example, we read the XML file named ‘example.xml’ and obtain the root element of the XML document. Once we have the ElementTree object, we can now perform pretty printing using the tostring() method with some additional parameters.
🌐
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
🌐
Python Module of the Week
pymotw.com › 3 › xml.etree.ElementTree › create.html
Building Documents With Element Nodes — PyMOTW 3
August 6, 2016 - from xml.etree.ElementTree import Element, SubElement, Comment from ElementTree_pretty import prettify top = Element('top') comment = Comment('Generated for PyMOTW') top.append(comment) child = SubElement(top, 'child') child.text = 'This child contains text.' child_with_tail = SubElement(top, 'child_with_tail') child_with_tail.text = 'This child has text.' child_with_tail.tail = 'And "tail" text.' child_with_entity_ref = SubElement(top, 'child_with_entity_ref') child_with_entity_ref.text = 'This & that' print(prettify(top)) ... $ python3 ElementTree_create_pretty.py <?xml version="1.0" ?> <top> <!--Generated for PyMOTW--> <child>This child contains text.</child> <child_with_tail>This child has text.</child_with_tail> And &quot;tail&quot; text.
🌐
DataCamp
datacamp.com › tutorial › python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - Since ElementTree is a powerful library that can interpret more than just XML. You must specify both the encoding and decoding of the document you are displaying as the string. For XMLs, use 'utf8' - This is the typical document format for an XML. print(ET.tostring(root, encoding='utf8').decode('utf8'))
🌐
sqlpey
sqlpey.com › python › how-to-pretty-print-xml-files-using-python-elementtree
How to Pretty Print XML Files Using Python's ElementTree - …
November 24, 2024 - One effective solution involves the use of the indent() function, which provides the ability to append whitespace for better visual indentation in your XML output. This function was introduced in Python 3.9, and here’s an example of how to use it: tree = ET.ElementTree(root) ET.indent(tree, ...
🌐
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.
🌐
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.