python code pretty print xml file in python

The following code demonstrates how to pretty print an XML file in Python using the minidom library.

main.py
import xml.dom.minidom

def prettify_xml(file_path):
    """
    Reads an XML file and pretty prints it
    """
    # Parse the XML file
    dom = xml.dom.minidom.parse(file_path)
    
    # Pretty print the XML document
    pretty_xml = dom.toprettyxml()
    
    # Write the pretty printed XML to a file
    with open(file_path, "w") as f:
        f.write(pretty_xml)
370 chars
16 lines

The function prettify_xml takes a file path as an argument, reads the XML file at that path, formats it with indentation and line breaks using toprettyxml(), and writes the formatted XML back to the same file.

You can call the function like this:

main.py
prettify_xml("path/to/your/xml/file.xml")
42 chars
2 lines

gistlibby LogSnag