如何用 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"/>
廣告