Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
Roman Alexander Avatar asked Mar 12 '13 08:03

Roman Alexander


People also ask

What is XML Etree ElementTree in Python?

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.

What is the XML declaration?

An XML declaration is a processing instruction that identifies a document as XML. DITA documents must begin with an XML declaration.

What does standalone mean in XML?

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.


2 Answers

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.

like image 104
wrgrs Avatar answered Sep 18 '22 16:09

wrgrs


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)) 
like image 39
glormph Avatar answered Sep 16 '22 16:09

glormph