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 printing XML in Python?
To pretty print XML in Python, we can use the xml.dom.minidom.parseString
method.
For instance, we write:
import xml.dom.minidom
xml_string = '''
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
'''
dom = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
print(pretty_xml_as_string)
We call xml.dom.minidom.parseString
with xml_string
to create the dom
object from the XML string.
Then we call dom.toprettyxml
to return a prettified version of the XML string.
Therefore, we see:
<?xml version="1.0" ?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
printed.
We can also call xml.dom.minidom.parse
with the XML file path and do the same thing.
For instance, we write:
file.xml
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
main.py
import xml.dom.minidom
dom = xml.dom.minidom.parse('file.xml')
pretty_xml_as_string = dom.toprettyxml()
print(pretty_xml_as_string)
and get the same result.
The only difference is that we pass in the file path to xml.dom.minidom.parse
.
Conclusion
To pretty print XML in Python, we can use the xml.dom.minidom.parseString
method.
We can also call xml.dom.minidom.parse
with the XML file path and do the same thing.