我想生產這種XML文件python
和minidom
:添加命名空間的DOM元素蟒蛇
<xml vesion="1.0" encoding="utf-8?>
<package name="Operation" xmlns="http://www.modelIL.eu/types-2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.modelIL.eu/types-2.0 modelIL-package-2.0.xsd">
</package>
我已經寫了這個:
import xml.dom.minidom as dom
document = dom.Document()
root_xml = document.createElement("package")
root_xml.setAttribute("name", "Operation")
root_xml.setAttributeNS("", "xmlns", "http://www.modelIL.eu/types-2.0")
root_xml.setAttributeNS("xmls", "xsi", "http://www.w3.org/2001/XMLSchema-instance")
root_xml.setAttribute("xsi:schemaLocation", "http://www.modelIL.eu/types-2.0 modelIL-package-2.0.xsd")
root = document.appendChild(root_xml)
print(document.toprettyxml(indent(" "))
但輸出我得到的是這樣的一種:
<xml vesion="1.0" ?>
<package name="Operation" xmlns="http://www.modelIL.eu/types-2.0" xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.modelIL.eu/types-2.0 modelIL-package-2.0.xsd">
</package>
爲什麼我只有xsi
而不是xmlns:xsi
?我忘了什麼嗎?
非常感謝你的回答。我更瞭解setAttributesNS,它幫助我解決了我的問題!對於你的問題,我綁定了'root = document.appendChild(root_xml)',因爲我發現它對我來說更容易理解,因爲我給其他函數的根添加了子元素。 – user3314570
很高興聽到!並感謝你對'root'的回答。 – dasdachs