How to generate XML documents with namespaces in Python?

PythonServer Side ProgrammingProgrammingXML

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"/>
raja
Published on 21-Dec-2017 16:19:12
Advertisements