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
🌐
GeeksforGeeks
geeksforgeeks.org › python › pretty-printing-xml-in-python
Pretty Printing XML in Python - GeeksforGeeks
July 23, 2025 - from bs4 import BeautifulSoup temp ... <Name> Sandeep Jain Sir </Name> </instructor> </gfg> In this method, we will be using the python lxml module....
🌐
Mainframeperformancetopics
mainframeperformancetopics.com › 2019 › 12 › 26 › pretty-printing-xml-in-python
Pretty Printing XML in Python – Mainframe, Performance, Topics
December 26, 2019 - So the following is a short Python program to pretty print an XML file. It takes the XML file as standard input (stdin) and writes the formatted XML to standard output (stdout).
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - If not given, the standard XMLParser parser is used. Returns the section root element. write(file, encoding='us-ascii', xml_declaration=None, default_namespace=None, method='xml', *, short_empty_elements=True)
🌐
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 - Or, we can also set the full path to the file in the filename variable. The prettify() function beautifies the output of the XML file. Note that the output has been trimmed for understanding purposes.
🌐
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.
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
ElementTree can be used to construct a similar XML file from a CSV input file, setting all of the element attributes as the tree is constructed. import csv from xml.etree.ElementTree import Element, SubElement, Comment, tostring import datetime from ElementTree_pretty import prettify generated_on = str(datetime.datetime.now()) # Configure one attribute with set() root = Element('opml') root.set('version', '1.0') root.append(Comment('Generated by ElementTree_csv_to_xml.py for PyMOTW')) head = SubElement(root, 'head') title = SubElement(head, 'title') title.text = 'My Podcasts' dc = SubElement(h
🌐
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, ... 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....
Find elsewhere
🌐
GitHub
gist.github.com › 3081869
Pretty printing XML in Python · GitHub
Save mahmoud/3081869 to your computer and use it in GitHub Desktop. Download ZIP · 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.
🌐
GeeksforGeeks
geeksforgeeks.org › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
August 10, 2024 - # The tag is found by the clause # `bs_data.find_all('child', {'name':'Frank'})` for tag in bs_data.find_all('child', {'name':'Frank'}): tag['test'] = "WHAT !!" # Output the contents of the # modified xml file print(bs_data.prettify()) ... Elementtree module provides us with a plethora of tools for manipulating XML files. The best part about it being its inclusion in the standard Python's built-in library.
🌐
Python
bugs.python.org › issue23847
Issue 23847: Add xml pretty print option to ElementTree - Python tracker
August 6, 2016 - 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
🌐
my tiny TechBlog
norwied.wordpress.com › 2013 › 08 › 27 › 307
Pretty print XML trees in python – my tiny TechBlog
June 1, 2018 - E = xml.etree.ElementTree.Element(‘root’) S = xml.etree.ElementTree.SubElement(‘kid’) S.set(‘attrib’, ‘value of attribute’) xmlindent(E) T = xml.etree.ElementTree.ElementTree(E) T.write(‘/file.name’,…) Thank you Chris for your contribution 🙂 · Comments are closed. Build gridlab-d v3.2 on Linux · First steps with my Nucleo-F401RE · Pretty print XML trees in python ·
🌐
Python
docs.python.org › 3 › library › xml.dom.minidom.html
xml.dom.minidom — Minimal DOM implementation
Write XML to the writer object. The writer receives texts but not bytes as input, it should have a write() method which matches that of the file object interface. The indent parameter is the indentation of the current node.
🌐
GitHub
gist.github.com › edison12a › 7247648fed8fa3c511b8edf55d91c029
Python script to pretty print XML files · GitHub
Python script to pretty print XML files. GitHub Gist: instantly share code, notes, and snippets.
🌐
Dive into Python
diveintopython.org › home › learn python programming › file handling and file operations › xml files handling
XML File Operations with Python - Read, Write and Parse XML Data
May 3, 2024 - In both of these examples, the xml.etree.ElementTree module is used to parse the XML file and extract the data. The csv module (in Example 1) or the pandas library (in Example 2) is used to write the data to a CSV file. Do not hesitate to contribute to Python tutorials on GitHub: create a fork, update content and issue a pull request.
Top answer
1 of 6
424

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5. Deprecated and folded into the regular ElementTree as an automatic thing as of 3.3.)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

  • API docs for the implementation in the Python standard library
  • Introductory Tutorial (From the original author's site)
  • LXML etree tutorial. (With example code for loading the best available option from all major ElementTree implementations)

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.
2 of 6
79

The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

#!/usr/bin/python
import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
        DOC(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),
            )   
        )   

print lxml.etree.tostring(the_doc, pretty_print=True)

Output:

<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </doc>
</root>

It also supports adding to an already-made node, e.g. after the above you could say

the_doc.append(FIELD2('another value again', name='hithere'))
🌐
py4u
py4u.org › blog › python-pretty-print-an-xml-given-an-xml-string
How to Pretty Print an XML String in Python Without Writing to a File: Top Tools and Methods
Validation: Manually verifying XML structure (e.g., missing tags) is simpler with proper formatting. In all these cases, writing to a file is unnecessary—you need the pretty-printed string directly in memory. Python 3.6+ (some methods require 3.9+ for built-in features).
🌐
sqlpey
sqlpey.com › python › python-pretty-print-xml
Python: How to Pretty Print XML - sqlpey
November 4, 2025 - The minidom module is part of Python’s standard XML processing suite and provides a straightforward method for pretty printing. import xml.dom.minidom xml_fname = 'your_document.xml' # or xml_string = '<root><item>value</item></root>' # Parse the XML file or string dom = xml.dom.minidom.parse(xml_fname) # Or for a string: dom = xml.dom.minidom.parseString(xml_string) # Generate a pretty-printed XML string pretty_xml_as_string = dom.toprettyxml() print(pretty_xml_as_string)
🌐
GitHub
gist.github.com › rspivak › c0ff66ec35a13b075011
Pretty print XML with lxml · GitHub
Save rspivak/c0ff66ec35a13b075011 to your computer and use it in GitHub Desktop. Download ZIP · Pretty print XML with lxml · Raw · ppxml · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.