How to write XML declaration using xml.etree.ElementTree

后端 未结 11 957
长情又很酷
长情又很酷 2020-11-30 05:11

I am generating an XML document in Python using an ElementTree, but the tostring function doesn\'t include an XML declaration when converting to plaintext.

11条回答
  •  我在风中等你
    2020-11-30 06:06

    This works if you just want to print. Getting an error when I try to send it to a file...

    import xml.dom.minidom as minidom
    import xml.etree.ElementTree as ET
    from xml.etree.ElementTree import Element, SubElement, Comment, tostring
    
    def prettify(elem):
        rough_string = ET.tostring(elem, 'utf-8')
        reparsed = minidom.parseString(rough_string)
        return reparsed.toprettyxml(indent="  ")
    

提交回复
热议问题