How to generate XML documents with namespaces in Python How to generate XML documents with namespaces in Python python python

How to generate XML documents with namespaces in Python


createElementNS() is defined as:

def createElementNS(self, namespaceURI, qualifiedName):    prefix, localName = _nssplit(qualifiedName)    e = Element(qualifiedName, namespaceURI, prefix)    e.ownerDocument = self    return e

so…

import xml.dom.minidomdoc = xml.dom.minidom.Document()el = doc.createElementNS('http://example.net/ns', 'ex:el')#--------------------------------------------------^^^^^doc.appendChild(el)print(doc.toprettyxml())

yields:

<?xml version="1.0" ?><ex:el/>

…not quite there…

import xml.dom.minidomdoc = xml.dom.minidom.Document()el = doc.createElementNS('http://example.net/ns', 'ex:el')el.setAttribute("xmlns:ex", "http://example.net/ns")doc.appendChild(el)print(doc.toprettyxml())

yields:

<?xml version="1.0" ?><ex:el xmlns:ex="http://example.net/ns"/>

alternatively:

import xml.dom.minidomdoc = xml.dom.minidom.Document()el = doc.createElementNS('http://example.net/ns', 'el')el.setAttribute("xmlns", "http://example.net/ns")doc.appendChild(el)print(doc.toprettyxml())

wich produces:

<?xml version="1.0" ?><el xmlns="http://example.net/ns"/>

It looks like you'd have to do it manually. Element.writexml() shows no indication that namespaces would get any special treatment.

EDIT: This answer is targeted at xml.dom.minidom only, since the OP used it in the question. I do not indicate that it was impossible to use XML namespaces in Python generally. ;-)


This feature is already proposed; a patch is slumbering in the Python bug database. See Tomalak's answer (in short: Manually add the xmlns attribute) for a workaround.