pretty print xml file in python

To pretty print an XML file in Python, you can use either the minidom or ElementTree module.

Using minidom:

main.py
import xml.dom.minidom
xml_string = "<root><element /><element /></root>"
dom = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
print(pretty_xml_as_string)
189 chars
6 lines

Using ElementTree:

main.py
import xml.etree.ElementTree as ET
xml_string = "<root><element /><element /></root>"
root = ET.fromstring(xml_string)
pretty_xml_as_string = ET.tostring(root, encoding='unicode')
print(pretty_xml_as_string)
208 chars
6 lines

Both approaches generate a pretty XML string with indentation and line breaks for easy readability.

gistlibby LogSnag