Categories
Python Answers

How to pretty print XML in Python?

Spread the love

Sometimes, we want to pretty print XML in Python.

In this article, we’ll look at how to pretty print XML in Python.

How to pretty print XML in Python?

To pretty print XML in Python, we can use the xml.dom.minidom module’s toprettyxml method.

For instance, we write

import xml.dom.minidom

dom = xml.dom.minidom.parse(xml_fname)
pretty_xml_as_string = dom.toprettyxml()

to parse the XML file at path xml_fname with xml.dom.minidom.parse into a DOM object.

Then we call toprettyxml on the DOM object to return the XML as a pretty printed string.

We can also parse XML from a string with

xml.dom.minidom.parseString(xml_string)

where xml_string is an XML string.

Conclusion

To pretty print XML in Python, we can use the xml.dom.minidom module’s toprettyxml method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *