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 Top answer 1 of 16
483
import xml.dom.minidom
dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
2 of 16
198
lxml is recent, updated, and includes a pretty print function
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)
Check out the lxml tutorial: https://lxml.de/tutorial.html
GeeksforGeeks
geeksforgeeks.org › python › pretty-printing-xml-in-python
Pretty Printing XML in Python - GeeksforGeeks
July 23, 2025 - In this approach, we will be using Beautiful Soup for printing the XML content. Python3 · from bs4 import BeautifulSoup temp = BeautifulSoup(open("gfg.xml"), "xml") new_xml = temp.prettify() print(new_xml) Output: <?xml version="1.0" encoding="utf-8"?> <gfg> <instructor> <Name> Sandeep Jain Sir </Name> </instructor> </gfg> In this method, we will be using the python lxml module.
Videos
03:02
What Is Pretty Printing XML? - Next LVL Programming - YouTube
15:10
Splunk: How to create XML pretty print formatter using custom command ...
01:11
PYTHON : Pretty printing XML in Python - YouTube
03:00
How to Change Tab Spacing in Python lxml PrettyPrint for XML ...
03:43
Pretty printing XML in Python - YouTube
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")
TutorialsPoint
tutorialspoint.com › pretty-printing-xml-in-python
Pretty Printing XML in Python
July 25, 2023 - 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.
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.
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.
ActiveState
code.activestate.com › recipes › 576750-pretty-print-xml
Pretty-print XML « Python recipes « ActiveState Code
May 13, 2009 - 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]) ...
Reddit
reddit.com › r/python › pycharm: how to pretty-print xml elements in the debugger
r/Python on Reddit: PyCharm: how to pretty-print XML elements in the debugger
December 14, 2015 -
I just met PyCharm, and I really like it. But the first thing I am using it for is to manipulate XML files, and I'd like the debugger to show the XML elements I'm building in an easily read format. I am using etree from the lxml module. The result of
print(headerElement, pretty_print=True)
is
b'<HEADER>\n <MESSAGE_NUMBER>0</MESSAGE_NUMBER>\n <SIMULATION_INDEX>N</SIMULATION_INDEX>\n</HEADER>\n'
I need the debugger to show me this:
<HEADER> <MESSAGE_NUMBER>0</MESSAGE_NUMBER> <SIMULATION_INDEX>N</SIMULATION_INDEX> </HEADER>
I am using Win7 Pro.
Thank you very much.
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
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 - Python · JavaScript · Data Science · Machine Learning · Courses · Linux · DevOps · Last Updated : 23 Jul, 2025 · To pretty print XML from the command line, we can employ two methods, xmllint and XMLStarlet.
Beautiful Soup
crummy.com › software › BeautifulSoup › bs4 › doc
Beautiful Soup Documentation — Beautiful Soup 4.14.3 documentation
You can change this behavior by providing a value for the formatter argument to prettify(), encode(), or decode(). Beautiful Soup recognizes five possible values for formatter. The default is formatter="minimal". Strings will only be processed enough to ensure that Beautiful Soup generates valid HTML/XML: french = "<p>Il a dit <<Sacré bleu!>></p>" soup = BeautifulSoup(french, 'html.parser') print(soup.prettify(formatter="minimal")) # <p> # Il a dit <<Sacré bleu!>> # </p>
Python
bugs.python.org › issue37940
Issue 37940: Add xml.tool to pretty print XML like json.tool - Python tracker
August 24, 2019 - 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/82121
Notepad++ Community
community.notepad-plus-plus.org › topic › 14344 › pretty-print-xml-by-default
pretty print XML by default? | Notepad++ Community
September 13, 2017 - The one line python script is : notepad.runPluginCommand(‘XML Tools’, ‘Pretty Print (XML only - with line breaks)’)
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: