我想使用 python
和 minidom
生成此 xml 文件:
<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
?我是不是忘记了什么?
最佳答案
全面披露:我不使用 minidom 来处理 XML,我使用 lxml最重要的是,我不经常使用 XML,所以我希望我的回答有用。
One might expect that by setting an attribute with a particular namespace, there would not be any need to explicitly state a prefix to appear before the local name in the final, written XML document - after all, it should be possible to detect that a namespace has been employed and that a prefix is required in the full attribute name so that the attribute is recognised as being associated with that namespace. Unfortunately, we do not seem to have that luxury and must explicitly specify a prefix as part of the qualified name when setting such an attribute
Python and XML: An Introduction (跳到属性部分)
这应该可以解决您的问题:
root_xml.setAttributeNS("xmls", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
如您所知,setAttributeNS方法采用三个参数:namespaceURI、qualifiedName、value。如果元素没有具有相同命名空间URI和本地名称的属性,则添加该属性 - 我们通过使用函数_nssplit对qualifiedName进行拆分来获取本地名称。 。否则该方法会尝试更新属性的值。
但是,属性的名称是前缀(冒号标点符号之前的qualifiedName部分)和本地名称“%s:%s”%(前缀,localName)
的组合。如果不存在前缀,则属性名称与 QualifiedName 参数相同。
如果您不关心属性的命名空间URI,您可以仅使用 setAttribute 获得相同的结果。方法就像您对第一个和最后一个属性所做的那样。在这种情况下,该方法将查找具有相同属性名称的属性。如果它找到一个,它会尝试覆盖它的值。
我确实有一个问题:为什么要绑定(bind)root = document.appendChild(root_xml)
?是为了避免你的REPL中的返回值吗?我明白了。
关于python - 将命名空间添加到 DOM 元素 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38263798/