How to generate XML documents with namespaces in Python?

Generating XML documents with namespaces in Python requires careful handling since the built-in xml.dom.minidom module has limited namespace support. While you can create namespaced elements, you need to manually add namespace declarations as attributes.

Creating XML with Namespaces Using minidom

The createElementNS() method creates an element with a namespace, but you must add the namespace declaration manually ?

import xml.dom.minidom

doc = xml.dom.minidom.Document()
element = doc.createElementNS('http://hello.world/ns', 'ex:el')
element.setAttribute("xmlns:ex", "http://hello.world/ns")
doc.appendChild(element)
print(doc.toprettyxml())
<?xml version="1.0" ?>
<ex:el xmlns:ex="http://hello.world/ns"/>

Creating Complex XML with Multiple Namespaces

For more complex XML documents with multiple namespaces and nested elements ?

import xml.dom.minidom

doc = xml.dom.minidom.Document()

# Root element with namespace
root = doc.createElementNS('http://example.com/ns1', 'ns1:root')
root.setAttribute("xmlns:ns1", "http://example.com/ns1")
root.setAttribute("xmlns:ns2", "http://example.com/ns2")
doc.appendChild(root)

# Child element with different namespace
child = doc.createElementNS('http://example.com/ns2', 'ns2:child')
child.appendChild(doc.createTextNode('Sample text'))
root.appendChild(child)

print(doc.toprettyxml(indent="  "))
<?xml version="1.0" ?>
<ns1:root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2">
  <ns2:child>Sample text</ns2:child>
</ns1:root>

Using lxml for Better Namespace Support

The lxml library provides better namespace handling capabilities ?

from lxml import etree

# Define namespaces
nsmap = {
    'ex': 'http://example.com/ns1',
    'ext': 'http://example.com/ns2'
}

# Create root element
root = etree.Element('{http://example.com/ns1}root', nsmap=nsmap)

# Add child elements
child = etree.SubElement(root, '{http://example.com/ns2}child')
child.text = 'Sample text'

# Convert to string
xml_string = etree.tostring(root, pretty_print=True, encoding='unicode')
print(xml_string)

Key Points

Method Namespace Support Complexity Best For
xml.dom.minidom Manual Medium Simple XML with basic namespaces
lxml Built-in Low Complex XML with multiple namespaces

Conclusion

While Python's built-in xml.dom.minidom can handle namespaces with manual attribute setting, lxml provides more robust namespace support. Choose minidom for simple cases or lxml for complex XML generation with multiple namespaces.

Updated on: 2026-03-24T17:17:55+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements