Python pretty print an XML given an XML string

前端 未结 3 1442
予麋鹿
予麋鹿 2020-12-17 17:56

I generated a long and ugly XML string with Python and I need to filter it through pretty printer to look nicer.

I found this post for python pretty printers, but I

3条回答
  •  攒了一身酷
    2020-12-17 18:35

    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. You mention that you have an xml string already so I am going to assume you used xml.dom.minidom.parseString()

    With the following solution you can avoid writing to a file first:

    import xml.dom.minidom
    import os
    
    def pretty_print_xml_given_string(input_string, output_xml):
        """
        Useful for when you are editing xml data on the fly
        """
        xml_string = input_string.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)
    

    I found how to fix the common newline issue here.

提交回复
热议问题