How to write XML declaration using xml.etree.ElementTree

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

    Another pretty simple option is to concatenate the desired header to the string of xml like this:

    xml = (bytes('\n', encoding='utf-8') + ET.tostring(root))
    xml = xml.decode('utf-8')
    with open('invoice.xml', 'w+') as f:
        f.write(xml)
    

提交回复
热议问题