Python:在lxml中添加名称空间

时间:2009-05-14 12:58:32

标签: python lxml xml-namespaces

我正在尝试使用与此示例类似的 lxml 指定名称空间(取自here):

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

我不确定如何添加要使用的Schema实例以及Schema位置。 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'

我不知道如何将它指定为实例,然后还指定一个位置。似乎可以使用nsmap中的etree.Element关键字-arg来完成此操作,但我看不出如何。

1 个答案:

答案 0 :(得分:8)

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

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

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

>>> location_attribute = '{%s}noNameSpaceSchemaLocation' % NS
>>> 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知道所讨论的命名空间的常用前缀是“xsi”。如果它不是一个众所周知的命名空间,你可能会看到像“ns0”,“ns1”等前缀...,除非你指定了你喜欢的前缀。 (记住:前缀不应该重要)