Skip to content
Muslu Yüksektepe

Xml_Beautifier

A small Python tool that automatically indents XML files to make them readable.

Xml_Beautifier is a short Python example I wrote in 2016 for indenting an XML file into a readable form. The repository holds a single file, and the lxml library does the work.

Purpose

XML files returned by services or produced by other systems often arrive in one piece, with no line breaks or indentation. An XML document with many nested tags is hard to read in that form, and finding the field you are looking for is harder still. I wrote this example to note down the shortest way, from within Python, to indent an XML file properly. It is part of a small series, together with the HTML, CSS, JavaScript, SQL and JSON indenting examples I made on the same day.

How it works

The script first imports the etree module from lxml. It then reads an XML file from disk with etree.parse and turns it into a tree. In the last step it turns that tree back into text with etree.tostring. The pretty_print=True setting passed to this call puts each tag on its own line and indents nested tags according to their depth. The result is printed to the screen.

Key features

  • Because it parses the XML first and then writes it out again, the indentation follows the real nesting of the tags.
  • If the file is not valid XML, parsing fails, so broken files are noticed as well.

Technical stack

The code is written in Python and its only external dependency is the lxml library. The example uses Python 2 syntax, where print is written without parentheses. The name of the file to read sits in the code as a fixed placeholder.

Status

This is a note-style example and has not been updated since 2016. To use it, replace the file name with your own XML file, and to run it on Python 3, turn the print line into a function call.

Use cases

  • It can be used to make an XML response from a web service readable before looking into it.
  • It helps keep XML files used for configuration or data exchange in a tidy form.
  • It can serve as a starting point when adding XML formatting to another Python tool.
Category
Developer tools
Year
2016

Technologies

  • Python
  • XML

Links

  • GitHub https://github.com/muslu/Xml_Beautifier

Back to all projects