我正在尝试使用类似于此示例的 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/