XML Pretty Print Using Python – With Examples

May 30, 2018

2 mins read

Published in

XML Pretty Print using Python is required frequently for testing, analyzing and debugging XML data. Python and XML both are treading in programming fields. Python generates dynamic XML string and received by the client. To save memory or bandwidth it’s better to send the minified version of XML text.

Some time for debugging purposes, we need to see beautified XML data to understand and to Debug. This article will help to pretty-print XML data.

There are two examples in the post.

  1. Pretty Print XML String
  2. Pretty Print XML File

1. XML Pretty Print using Python

Here is an example:

1
2
3
4
5
6
7
8
9
import xml.dom.minidom

uglyxml = '<?xml version="1.0" encoding="UTF-8" ?><employees><employee><Name>Leonardo DiCaprio</Name></employee></employees>'

xml = xml.dom.minidom.parseString(uglyxml)

xml_pretty_str = xml.toprettyxml()

print xml_pretty_str

Result :

1
2
3
4
5
6
<?xml version="1.0" ?>
<employees>
  <employee>
    <Name>Leonardo DiCaprio</Name>
  </employee>
</employees>

Here is the explanation for the code.

  1. import xml.dom.minidom

This is an XML library available in python to convert the DOM object from XML string or from the XML file.

  1. xml.dom.minidom.parseString

parseString is a method which converts XML string to objectxml.dom.minidom.Document.

  1. xml.toprettyxml

toprettyxml This method will indent the XML data and return as Pretty XML string.

2. XML Print Print from File using Python

Here is the Example:

1
2
3
4
5
6
7
import xml.dom.minidom

with open('xmlfile.xml') as xmldata:
    xml = xml.dom.minidom.parseString(xmldata.read())  # or xml.dom.minidom.parseString(xml_string)
    xml_pretty_str = xml.toprettyxml()

print xml_pretty_str

This program reads from file and load and create XML Document objects and print the XML data in beautiful XML String.

I have used these tools for creating this blog post.

XML Formatter

XML Viewer

Related articles:

JSON Pretty Print using Python

Sharing is caring!