代码之家  ›  专栏  ›  技术社区  ›  Jason Coon

python:在lxml中添加名称空间

  •  6
  • Jason Coon  · 技术社区  · 17 年前

    我正在尝试使用 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'
    

    不过,我不知道如何将其指定为实例,然后还要指定位置。这似乎可以用 nsmap 关键字ARG etree.Element 但是我不知道怎么做。

    1 回复  |  直到 12 年前
        1
  •  8
  •   Steve    17 年前

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

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