Pretty printing XML in Python

后端 未结 26 1756
一个人的身影
一个人的身影 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 03:03

    For converting an entire xml document to a pretty xml document
    (ex: assuming you've extracted [unzipped] a LibreOffice Writer .odt or .ods file, and you want to convert the ugly "content.xml" file to a pretty one for automated git version control and git difftooling of .odt/.ods files, such as I'm implementing here)

    import xml.dom.minidom
    
    file = open("./content.xml", 'r')
    xml_string = file.read()
    file.close()
    
    parsed_xml = xml.dom.minidom.parseString(xml_string)
    pretty_xml_as_string = parsed_xml.toprettyxml()
    
    file = open("./content_new.xml", 'w')
    file.write(pretty_xml_as_string)
    file.close()
    

    References:
    - Thanks to Ben Noland's answer on this page which got me most of the way there.

提交回复
热议问题