Copyimport 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
🌐
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, we will be using the python lxml module.
Discussions

PyCharm: how to pretty-print XML elements in the debugger
I suppose you meant: print(etree.tostring(headerElement, pretty_print=True)) (print function does not have a pretty_print argument) In that case you either have to decode it afterwards, because it returns a bytestring (but for that you have to know the encoding, which is probably utf-8 though, nope, it's ascii, and non-ascii are escaped in the 東方 form). Or you just specify the return encoding, where "unicode" is a special value, telling it to return a unicode string instead of an encoded bytestring: print(etree.tostring(headerElement, pretty_print=True, encoding='unicode')) Edit: some additions here and there More on reddit.com
🌐 r/Python
2
5
December 14, 2015
Proper indentation or perry print using ElementTree(XML)

Someone please help me. I've been stuck on this assingment for whole day now :( Why my program only adds the last value from list into my XML file? The output is right but for some reason my program only adds 1 value to the list. I loop over the list which contains every item and therefore my program should add every item from that list into the XML file

My code,output and desired output:https://pastebin.com/pWiWi2MW

More on reddit.com
🌐 r/learnpython
5
6
November 6, 2017
LXML: Adding line break for readability
You could use indent() after adding your comments - which will add newlines and indent each line. You could then add a newline to the tail of each previous sibling of the comments. e.g. from lxml import etree root_node = etree.Element('RootNode') parent_node = etree.Element('ParentNode', addr="0x00") comment_count = 0 for i in range(0, 8): if i % 2 == 0: comment_str = 'Comment ID {}'.format(comment_count) comment_node = etree.Comment(comment_str) comment_count += 1 parent_node.append(comment_node) parent_node.append(etree.Element("ChildNode", foo_attr='foo', bar_attr='bar')) root_node.append(parent_node) etree.indent(root_node) children = root_node.findall('.//ChildNode') for i, tag in enumerate(children): if i % 2 == 1 and i < len(children) - 1: tag.tail = '\n' + tag.tail print(etree.tostring(root_node, encoding='utf-8', xml_declaration=True).decode()) More on reddit.com
🌐 r/learnpython
3
0
September 8, 2022
Document Management Systems?
Can you print bardcodes? An omnidirectional barcode scanner might be a lot less painful. If you can get a 2D barcode scanner, you’d be surprised how much info you can encode in a single barcode. For example, drivers licenses in the US pack the entire DL text (formatted!) into the stacked PDF417 barcode at the bottom. More on reddit.com
🌐 r/sysadmin
3
1
August 20, 2025
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
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 ...
🌐
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.
🌐
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")
🌐
PyPI
pypi.org › project › xmlformatter
xmlformatter · PyPI
xmlformatter is an Open Source Python package, which provides formatting of XML documents. It is the replacement for the Python 2 package XmlFormatter, which has been removed from PyPi completely (see Notes). xmlformatter differs from others formatters by handling whitespaces by a distinct set of formatting rules - formatting element content by a object style and mixed content by a text style.
      » pip install xmlformatter
    
Published   May 06, 2026
Version   0.2.9
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › article › pretty-printing-xml-in-python
Pretty Printing XML in Python
March 27, 2026 - The xml.dom.minidom module provides a lightweight DOM implementation that makes pretty printing straightforward with its built-in toprettyxml() method. import xml.dom.minidom def pretty_print_xml_minidom(xml_string): # Parse the XML string dom ...
🌐
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
🌐
Codemia
codemia.io › knowledge-hub › path › pretty_printing_xml_in_python
Pretty printing XML in Python
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
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 ·
🌐
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.

🌐
Linux Hint
linuxhint.com › xml-pretty-print-linux-bash-and-python
XML Pretty Print in Linux Bash and Python – Linux Hint
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: We can then run our Python script on the terminal to get the pretty formatted output as illustrated ...
🌐
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]) ...
🌐
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.
🌐
JSON Formatter
jsonformatter.org › xml-pretty-print
Best XML Pretty Print Online
This can be used as Sims 4 Pretty XML tool which helps to debug XML Injection for SIMS 4 MOD · Know more about XML: How to Print XML? Python XML Pretty Print · How to create XML File? Best and Secure XML Pretty Print works well in Windows, Mac, Linux, Chrome, Firefox, Safari and Edge.
🌐
Cloudzenia
cloudzenia.com › tools › xml-pretty-print
XML Pretty Print - Enhance Readability and Organize XML Data
Pretty printing makes the XML readable and error-free, regardless of the size of the data set or the complexity of the configuration file you are working on. With tools accessible across different platforms—from pretty print XML in Linux to pretty print XML Java, HTML, and Python—developers ...
🌐
GitHub
gist.github.com › tshenolo › 6f54aea88364c72baa4c94379b93d766
Python xml pretty print · GitHub
Python xml pretty print. GitHub Gist: instantly share code, notes, and snippets.
🌐
Tomatohater
tomatohater.com › 2010 › 10 › 20 › pretty-print-xml-and-json-in-python
Tomatohater: Pretty print xml (and json) in Python
October 20, 2010 - from xml.dom import minidom # from a string minidom.parseString(xml_string).toprettyxml(indent=' '*4) # or from a file minidom.parse(open(xml_file)).toprettyxml(indent=' '*4)