How to write an XML file without header in Python?

Unfortunately minidom does not give you the option to omit the XML Declaration.

But you can always serialise the document content yourself by calling toxml() on the document's root element instead of the document. Then you won't get an XML Declaration:

xml= document.documentElement.toxml('utf-8')

...but then you also wouldn't get anything else outside the root element, such as the DOCTYPE, or any comments or processing instructions. If you need them, serialise each child of the document object one by one:

xml= '\n'.join(node.toxml('utf-8') for node in document.childNodes)

I wondered if there are other packages which do allow to neglect the header.

DOM Level 3 LS defines an xml-declaration config parameter you can use to suppress it. The only Python implementation I know of is pxdom, which is thorough on standards support, but not at all fast.


If you want to use minidom and maintain 'prettiness', how about this as a quick/hacky fix:

xml_without_declaration.py:

import xml.dom.minidom as xml

doc = xml.Document()

declaration = doc.toxml()

a = doc.createElement("A")
doc.appendChild(a)
b = doc.createElement("B")
a.appendChild(b)

xml = doc.toprettyxml()[len(declaration):]

print xml

Tags:

Python

Xml