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: 2019-10-01T11:36:28+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements