How to write XML declaration using xml.etree.ElementTree

后端 未结 11 959
长情又很酷
长情又很酷 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 05:49

    Including 'standalone' in the declaration

    I didn't found any alternative for adding the standalone argument in the documentation so I adapted the ET.tosting function to take it as an argument.

    from xml.etree import ElementTree as ET
    
    # Sample
    document = ET.Element('outer')
    node = ET.SubElement(document, 'inner')
    et = ET.ElementTree(document)
    
     # Function that you need   
     def tostring(element, declaration, encoding=None, method=None,):
         class dummy:
             pass
         data = []
         data.append(declaration+"\n")
         file = dummy()
         file.write = data.append
         ET.ElementTree(element).write(file, encoding, method=method)
         return "".join(data)
    # Working example
    xdec = """"""    
    xml = tostring(document, encoding='utf-8', declaration=xdec)
    

提交回复
热议问题