Writing XML with namespaces from minidom

Although python’s minidom XML DOM implementation supports namespaces when you parse and create nodes, it bizarrely has no way to write out XML including the proper declarations:

<code>>>> import xml.dom.minidom
>>> from xml.dom import minidom
>>> impl = minidom.getDOMImplementation()
>>> doc = impl.createDocument("urn:tempuri", "e", None)
>>> doc.toprettyxml()
'<?xml version="1.0" ?>\n<e/>\n'</code>

Look, no namespace!

Fortunately, you can use the PyXML package to write out the xml properly. Install PyXML from sourceforge and then use like this:

<code>>>> from xml.dom.ext import PrettyPrint
>>> PrettyPrint(doc)
<?xml version='1.0' encoding='UTF-8'?>
<e xmlns='urn:tempuri'/></code>

Note that if you don’t want pretty printing you can use “Print” instead of “PrettyPrint”.

If you want to store the XML in a string instead of just printing it to stdout (imagine that - actually wanting to use the result of PrettyPrint!) then you need to provide a stream:

<code>>>> import StringIO
>>> s = StringIO.StringIO()
>>> PrettyPrint(doc, s)
>>> s.getvalue()
"<?xml version='1.0' encoding='UTF-8'?>\n<e xmlns='urn:tempuri'/>\n"
</code>