Python:在lxm中添加名称空间

2024-10-05 14:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图使用类似于此示例的lxml指定命名空间(取自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关键字arg完成,但我不知道如何实现。


Tags: 实例instanceorgtreehttpwww模式xmlschema
1条回答
网友
1楼 · 发布于 2024-10-05 14:26:42

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

>>> 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”等前缀,除非您指定了首选的前缀。(记住:前缀并不重要)

相关问题 更多 >