Python:在 lxml 中添加命名空间

标签 python lxml xml-namespaces

我正在尝试使用类似于此示例的 lxml 指定 namespace (取自 here ):

<TreeInventory xsi:noNamespaceSchemaLocation="Trees.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</TreeInventory>

我不确定如何添加要使用的架构实例以及架构位置。 documentation通过做类似的事情让我开始:

>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'
>>> TREE = '{%s}' % NS
>>> NSMAP = {None: NS}
>>> tree = etree.Element(TREE + 'TreeInventory', nsmap=NSMAP)
>>> etree.tostring(tree, pretty_print=True)
'<TreeInventory xmlns="http://www.w3.org/2001/XMLSchema-instance"/>\n'

虽然我不确定如何为它指定一个实例,然后再指定一个位置。这似乎可以通过 etree.Element 中的 nsmap 关键字参数来完成,但我不知道该怎么做。

最佳答案

为了清楚起见,在更多步骤中:

>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'

据我所知,您想要命名空间的是属性 noNamespaceSchemaLocation,而不是 TreeInventory 元素。所以:

>>> location_attribute = '{%s}noNamespaceSchemaLocation' % NS    # f-string doesn't work in this case
>>> elem = etree.Element('TreeInventory', attrib={location_attribute: 'Trees.xsd'})
>>> etree.tostring(elem, pretty_print=True)
'<TreeInventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Trees.xsd"/>\n'

这看起来像你想要的...... 当然,您也可以先创建不带属性的元素,然后设置属性,如下所示:

>>> elem = etree.Element('TreeInventory')
>>> elem.set(location_attribute, 'Trees.xsd')

至于nsmap参数:我相信它只是用来定义在序列化时使用哪些前缀。在这种情况下,不需要它,因为 lxml 知道相关 namespace 的常用前缀是“xsi”。如果它不是一些众所周知的命名空间,您可能会看到诸如“ns0”、“ns1”等前缀,除非您指定了您喜欢的前缀。 (记住:前缀不重要)

关于Python:在 lxml 中添加命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/863183/

相关文章:

Python - 通过计算从列表创建元组的最快方法

python - Python 中的元组到底是什么?

python - 更改 lxml 中子元素的默认命名空间

python - lxml - 类型错误 : write() got an unexpected keyword argument 'default_namespace'

objective-c - NSXML 添加命名空间以使 XPath 查询工作

python - 如何让python在将字符串写入文件时使用双引号

python - 如何启动 rpyc 服务器?

python - lxml findall 和倒序

c# - 在具有命名空间前缀的元素内创建不带命名空间前缀的 XML 元素

c# - 为什么 XML 序列化程序在使用 namespace 的对象反序列化时返回 null?