createElementNS()定义为:
def createElementNS(self, namespaceURI, qualifiedName):
prefix, localName = _nssplit(qualifiedName)
e = Element(qualifiedName, namespaceURI, prefix)
e.ownerDocument = self
return e
所以…
import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.createElementNS('http://example.net/ns', 'ex:el')
#--------------------------------------------------^^^^^
doc.appendChild(el)
print(doc.toprettyxml())
产量:
…不完全在那里
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())
产量:
或者:
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())
生产:
看起来你必须手动进行。 Element.writexml()没有显示命名空间会得到任何特殊的处理。
编辑:此答案仅针对xml.dom.minidom,因为OP在问题中使用它。一般来说,我并不表示在Python中使用XML命名空间是不可能的。 😉