Pretty printing XML in Python

676    Asked by RutujaMishra in Python , Asked on Apr 8, 2021

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

Answered by Rutuja Mishra

There are many ways for Python XML Pretty print some of the important are as follows:

import xml.dom.minidom
dom = xml.dom.minidom.parse(xml_fname)
pretty_xml_as_string = dom.toprettyxml()
Another thing you can use that lxml has recently, updated, that includes a pretty print function. Below is the code for the same.
import lxml.etree as etree
x = etree.parse("filename")
print(etree.tostring(x, pretty_print=True))

Your Answer

Interviews

Parent Categories