inserting newlines in xml file generated via xml.etree.ElementTree in python

前端 未结 5 1615
北海茫月
北海茫月 2020-12-02 17:12

I have created a xml file using xml.etree.ElementTree in python. I then use

tree.write(filename, "UTF-8") 

to write out the documen

5条回答
  •  执笔经年
    2020-12-02 17:41

    According to this thread your best bet would be installing pyXml and use that to prettyprint the ElementTree xml content (as ElementTree doesn't seem to have a prettyprinter by default in Python):

    import xml.etree.ElementTree as ET
    
    from xml.dom.ext.reader import Sax2
    from xml.dom.ext import PrettyPrint
    from StringIO import StringIO
    
    def prettyPrintET(etNode):
        reader = Sax2.Reader()
        docNode = reader.fromString(ET.tostring(etNode))
        tmpStream = StringIO()
        PrettyPrint(docNode, stream=tmpStream)
        return tmpStream.getvalue()
    

提交回复
热议问题