Search code examples
pythonxmlelementtree

How to write XML declaration using xml.etree.ElementTree


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.

from xml.etree.ElementTree import Element, tostring

document = Element('outer')
node = SubElement(document, 'inner')
node.NewValue = 1
print tostring(document)  # Outputs "<outer><inner /></outer>"

I need my string to include the following XML declaration:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

However, there does not seem to be any documented way of doing this.

Is there a proper method for rendering the XML declaration in an ElementTree?


Solution

  • I am surprised to find that there doesn't seem to be a way with ElementTree.tostring(). You can however use ElementTree.ElementTree.write() to write your XML document to a fake file:

    from io import BytesIO
    from xml.etree import ElementTree as ET
    
    document = ET.Element('outer')
    node = ET.SubElement(document, 'inner')
    et = ET.ElementTree(document)
    
    f = BytesIO()
    et.write(f, encoding='utf-8', xml_declaration=True) 
    print(f.getvalue())  # your XML file, encoded as UTF-8
    

    See this question. Even then, I don't think you can get your 'standalone' attribute without writing prepending it yourself.