How to write XML declaration using xml.etree.ElementTree
02:07 12 Mar 2013

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 ""

I need my string to include the following XML declaration:


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?

python xml elementtree