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?
The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.
An XML declaration is a processing instruction that identifies a document as XML. DITA documents must begin with an XML declaration.
The XML standalone element defines the existence of an externally-defined DTD. In the message tree it is represented by a syntax element with field type XML. standalone. The value of the XML standalone element is the value of the standalone attribute in the XML declaration.
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.
I would use lxml (see http://lxml.de/api.html).
Then you can:
from lxml import etree document = etree.Element('outer') node = etree.SubElement(document, 'inner') print(etree.tostring(document, xml_declaration=True)) 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With