How to generate XML documents with namespaces in Python?


Currently you cannot add namespaces to XML documents directly as it is not yet supported in the in built Python xml package. So you will need to add namespace as a normal attribute to the tag. For example,

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())

This will give you the document,

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

Updated on: 01-Oct-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements