【问题标题】:Clashing namespaces with lxml etree使用 lxml etree 冲突命名空间
【发布时间】:2012-09-12 14:06:59
【问题描述】:

我在 lxml 2.3 和 etree 中的命名空间存在问题。

例如,我有两个具有不同命名空间的节点:

parent = etree.Element('{parent-space}parent')
child = etree.Element('{child-space}child')

之后,child 节点被附加到parent 节点:

parent.append(child)

然后,如果我使用 etree 的tostring 方法,我会得到以下输出:

<ns0:parent xmlns:ns0="parent-space">
    <ns0:child xmlns:ns0="child-space"/>
</ns0:parent>

两个命名空间都在此处获得标签ns0,因此它们发生冲突。我怎样才能避免这种情况?

【问题讨论】:

    标签: python xml lxml xml-namespaces elementtree


    【解决方案1】:

    没有冲突。 ns0 前缀只是被 &lt;child&gt; 的后代覆盖。

    这个 XML 文档

    <ns0:parent xmlns:ns0="parent-space">
        <ns0:child xmlns:ns0="child-space"/>
    </ns0:parent>
    

    等价于

    <ns0:parent xmlns:ns0="parent-space">
        <ns1:child xmlns:ns1="child-space"/>
    </ns0:parent>
    

    <parent xmlns="parent-space">
        <child xmlns="child-space"/>
    </parent>
    

    parentchild的有效命名空间而言。

    您可以使用 nsmap 来声明前缀。有效的结果是一样的,但是序列化后看起来不那么混乱了。

    from lxml import etree
    
    NS_MAP = {
        "p" : "http://parent-space.com/",
        "c" : "http://child-space.com/"
    }
    NS_PARENT = "{%s}" % NS_MAP["parent"]
    NS_CHILD = "{%s}" % NS_MAP["child"]
    
    parent = etree.Element(NS_PARENT + "parent", nsmap=NS_MAP)
    child  = etree.SubElement(parent, NS_CHILD + "child")
    child.text = "Some Text"
    
    print etree.tostring(parent, pretty_print=True)
    

    打印出来

    <p:parent xmlns:p="http://parent-space.com/" xmlns:c="http://child-space.com/">
      <c:child>Some Text</c:child>
    </p:parent>
    

    【讨论】:

      【解决方案2】:

      看起来像这个帖子How to tell lxml.etree.tostring(element) not to write namespaces in python?建议使用cleanup_namespaces

      希望这会有所帮助

      【讨论】:

      • 清理命名空间只是删除未使用的命名空间,但不会将命名空间重新映射到唯一名称。
      猜你喜欢
      • 2018-07-10
      • 2011-05-14
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 2010-11-15
      相关资源
      最近更新 更多