我正试图使用类似于此示例的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完成,但我不知道如何实现。
在更多步骤中,为了清楚起见:
据我所见,您需要的是属性
noNameSpaceSchemaLocation
,而不是TreeInventory
元素。所以:这看起来像你想要的。。。 当然,也可以先创建不带属性的元素,然后设置属性,如下所示:
至于
nsmap
参数:我相信它只用于定义序列化时使用的前缀。在这种情况下,不需要它,因为lxml知道所讨论的名称空间的常用前缀是“xsi”。如果不是某个众所周知的名称空间,您可能会看到诸如“ns0”、“ns1”等前缀,除非您指定了首选的前缀。(记住:前缀并不重要)相关问题 更多 >
编程相关推荐