Pretty printing XML in Python

后端 未结 26 1816
一个人的身影
一个人的身影 2020-11-22 02:18

What is the best way (or are the various ways) to pretty print XML in Python?

26条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 02:47

    Here's a Python3 solution that gets rid of the ugly newline issue (tons of whitespace), and it only uses standard libraries unlike most other implementations.

    import xml.etree.ElementTree as ET
    import xml.dom.minidom
    import os
    
    def pretty_print_xml_given_root(root, output_xml):
        """
        Useful for when you are editing xml data on the fly
        """
        xml_string = xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml()
        xml_string = os.linesep.join([s for s in xml_string.splitlines() if s.strip()]) # remove the weird newline issue
        with open(output_xml, "w") as file_out:
            file_out.write(xml_string)
    
    def pretty_print_xml_given_file(input_xml, output_xml):
        """
        Useful for when you want to reformat an already existing xml file
        """
        tree = ET.parse(input_xml)
        root = tree.getroot()
        pretty_print_xml_given_root(root, output_xml)
    

    I found how to fix the common newline issue here.

提交回复
热议问题