How to write XML declaration using xml.etree.ElementTree
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 BytesIOfrom xml.etree import ElementTree as ETdocument = 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.
I would use lxml (see http://lxml.de/api.html).
Then you can:
from lxml import etreedocument = etree.Element('outer')node = etree.SubElement(document, 'inner')print(etree.tostring(document, xml_declaration=True))
If you include the encoding='utf8'
, you will get an XML header:
xml.etree.ElementTree.tostring writes a XML encoding declaration with encoding='utf8'
Sample Python code (works with Python 2 and 3):
import xml.etree.ElementTree as ElementTreetree = ElementTree.ElementTree( ElementTree.fromstring('<xml><test>123</test></xml>'))root = tree.getroot()print('without:')print(ElementTree.tostring(root, method='xml'))print('')print('with:')print(ElementTree.tostring(root, encoding='utf8', method='xml'))
Python 2 output:
$ python2 example.pywithout:<xml><test>123</test></xml>with:<?xml version='1.0' encoding='utf8'?><xml><test>123</test></xml>
With Python 3 you will note the b
prefix indicating byte literals are returned (just like with Python 2):
$ python3 example.pywithout:b'<xml><test>123</test></xml>'with:b"<?xml version='1.0' encoding='utf8'?>\n<xml><test>123</test></xml>"