Pretty printing XML in Python

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

    I had some problems with minidom's pretty print. I'd get a UnicodeError whenever I tried pretty-printing a document with characters outside the given encoding, eg if I had a β in a document and I tried doc.toprettyxml(encoding='latin-1'). Here's my workaround for it:

    def toprettyxml(doc, encoding):
        """Return a pretty-printed XML document in a given encoding."""
        unistr = doc.toprettyxml().replace(u'',
                              u'' % encoding)
        return unistr.encode(encoding, 'xmlcharrefreplace')
    

提交回复
热议问题