Pretty printing XML in Python


Question

What is the best way (or are the various ways) to pretty print XML in Python?

1
391
6/21/2019 1:45:27 PM

Accepted Answer

import xml.dom.minidom

dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
353
1/21/2019 2:02:32 PM

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: http://lxml.de/tutorial.html


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon