How to write XML declaration using xml.etree.ElementTree

后端 未结 11 963
长情又很酷
长情又很酷 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:46

    The minimal working example with ElementTree package usage:

    import xml.etree.ElementTree as ET
    
    document = ET.Element('outer')
    node = ET.SubElement(document, 'inner')
    node.text = '1'
    res = ET.tostring(document, encoding='utf8', method='xml').decode()
    print(res)
    

    the output is:

    
    1
    

提交回复
热议问题