I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom:
import xml.dom.minidom doc = xml.dom.minidom.Document() el = doc.createElementNS('http://example.net/ns', 'el') doc.appendChild(el) print(doc.toprettyxml())
The namespace is saved (doc.childNodes[0].namespaceURI
is 'http://example.net/ns'
), but why is it missing in the output?
<?xml version="1.0" ?> <el/>
I expect:
<?xml version="1.0" ?> <el xmlns="http://example.net/ns" />
or
<?xml version="1.0" ?> <randomid:el xmlns:randomid="http://example.net/ns" />
XML Namespaces - The xmlns Attribute When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
Creating XML Document using Python First, we import minidom for using xml. dom . Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks.
An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.
One of the primary motivations for defining an XML namespace is to avoid naming conflicts when using and re-using multiple vocabularies. XML Schema is used to create a vocabulary for an XML instance, and uses namespaces heavily.
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.minidom doc = 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.minidom doc = 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.minidom doc = 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. ;-)
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