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
🌐
TutorialsPoint
tutorialspoint.com › pretty-printing-xml-in-python
Pretty Printing XML in Python
Remove empty lines: By default, `toprettyxml()` adds empty lines in the output. To remove these empty lines, we split the pretty XML string by newlines (`\n`), remove any leading or trailing whitespace from each line, and then join the non-empty lines back together. Print the pretty XML: Finally, we print the resulting pretty XML string.
🌐
GeeksforGeeks
geeksforgeeks.org › python › pretty-printing-xml-in-python
Pretty Printing XML in Python - GeeksforGeeks
July 23, 2025 - from bs4 import BeautifulSoup temp = BeautifulSoup(open("gfg.xml"), "xml") new_xml = temp.prettify() print(new_xml) ... <?xml version="1.0" encoding="utf-8"?> <gfg> <instructor> <Name> Sandeep Jain Sir </Name> </instructor> </gfg> In this method, ...
🌐
Mainframeperformancetopics
mainframeperformancetopics.com › 2019 › 12 › 26 › pretty-printing-xml-in-python
Pretty Printing XML in Python – Mainframe, Performance, Topics
December 26, 2019 - #!/usr/bin/python from xml.dom import minidom from xml.parsers.expat import ExpatError import sys,re # Edit the following to control pretty printing indent=" " newl="" encoding="UTF-8" # Regular expression to find trailing spaces before a newline trails=re.compile(' *\n') try: # Parse the XML - from stdin dom=minidom.parse(sys.stdin) # First-pass Pretty Print of the XML prettyXML=dom.toprettyxml(indent,newl,encoding) # Further clean ups prettyXML=prettyXML.replace("\t","") prettyXML=prettyXML.replace('"?><','"?>\n<') prettyXML=re.sub(trails,"\n",prettyXML) # Write XML to stdout sys.stdout.write(prettyXML) except ExpatError as (expatError): sys.stderr.write("Bad XML: line "+str(expatError.lineno)+" offset "+str(expatError.offset)+"\n")
🌐
Codeblogmoney
codeblogmoney.com › xml-pretty-print-using-python-with-examples
XML Pretty Print using Python – with Examples
May 30, 2018 - Python generates dynamic XML string and received by the client. To save memory or bandwidth it’s better to send the minified version of XML text. 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.
🌐
Delft Stack
delftstack.com › home › howto › python › python xml pretty print
How to Pretty Print XML Output Pretty in Python | Delft Stack
February 16, 2024 - Refer to the following Python code for the same. from lxml import etree filename = "./books.xml" f = etree.parse(filename) content = etree.tostring(f, pretty_print=True, encoding=str) print(content)
Find elsewhere
🌐
ActiveState
code.activestate.com › recipes › 576750-pretty-print-xml
Pretty-print XML « Python recipes « ActiveState Code
The "pretty_print" function is a one-liner that produces clean-looking XML using this function, indenting by just 2 spaces by default and removing the junk new-lines. ... from xml.dom.ext import PrettyPrint from xml.dom.ext.reader.Sax import FromXmlFile import sys doc = FromXmlFile(sys.argv[1]) ...
🌐
GitHub
gist.github.com › 3081869
Pretty printing XML in Python · GitHub
Pretty printing XML in Python · Raw · pretty_print_xml.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.
🌐
Linux Hint
linuxhint.com › xml-pretty-print-linux-bash-and-python
XML Pretty Print in Linux Bash and Python – Linux Hint
Once imported, you can use the Python open() to read the contents of your external file. After that, you can use the toprettyxml() to print your external XML file pretty. In the following example, we use our external “details.xml” file and create different variables in the code:
🌐
my tiny TechBlog
norwied.wordpress.com › 2013 › 08 › 27 › 307
Pretty print XML trees in python – my tiny TechBlog
June 1, 2018 - I am using ElementTree, which does not support pretty printing using the pprint library. To circumvent this, I found this helpful webpage: http://effbot.org/zone/element-lib.htm#prettyprint · Now I would like to share some sample code to illustrate how you can use this function to make you xml look nice: 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
🌐
GitHub
gist.github.com › t2y › 4191973
python 1 liner for xml pretty print with standard input · GitHub
python -c "import sys; from xml.dom.minidom import parse; print(parse(sys.stdin).toprettyxml(indent=' '))"
🌐
GeeksforGeeks
geeksforgeeks.org › web tech › how-to-pretty-print-xml-from-the-command-line
How to Pretty Print XML from the Command Line? - GeeksforGeeks
July 23, 2025 - To pretty print XML from the command line, we can employ two methods, xmllint and XMLStarlet. With xmllint, included in the libxml2-utils package.
🌐
PyPI
pypi.org › project › xmlformatter
Pypi
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
GitHub
gist.github.com › edison12a › 7247648fed8fa3c511b8edf55d91c029
Python script to pretty print XML files · GitHub
Python script to pretty print XML files · Raw · xmlpp.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.
🌐
Narkive
tutor.python.narkive.com › HewyHE4O › pretty-printing-xml-using-lxml-on-python3
[Tutor] Pretty printing XML using LXML on Python3
s = etree.tounicode(root, pretty_print=True) print(s) <root> <child/> <child>some text</child> </root> ... 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 ...
🌐
WebScraping.AI
webscraping.ai › faq › lxml › is-there-a-way-to-pretty-print-html-or-xml-with-lxml
Is there a way to pretty print HTML or XML with lxml? | WebScraping.AI
The pretty_print parameter in the tostring() function automatically formats your output with proper indentation and line breaks. For XML documents, use etree.tostring() with pretty_print=True: