如何在Python中使用命名空间生成XML文档?

当前,您无法直接将命名空间添加到XML文档,因为内置的Python xml包尚不支持命名空间。因此,您需要将命名空间添加为标记的常规属性。例如,

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://example.net/ns"/>