如何在 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"/>

更新時間: 2019 年 10 月 1 日

2000+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.