首页 > 解决方案 > lxml 错误:lxml.etree.XPathEvalError:带有后代的无效表达式

问题描述

因为我也是 python 和 lxml 的新手,所以无法理解这个错误。下面是我的 xml 文本。

<node id="n25::n1">
  <data key="d5" xml:space="preserve"><![CDATA[ronin_sanity]]></data>
  <data key="d6">
    <ShapeNode>
      <Geometry height="86.25" width="182.0" x="3164.9136178770227" y="1045.403736953325"/>
      <Fill color="#C0C0C0" transparent="false"/>
      <BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
      <NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="83.376953125" x="49.3115234375" xml:space="preserve" y="33.7744140625">Messages App</NodeLabel>
      <Shape type="ellipse"/>
    </ShapeNode>
  </data>
</node>

这是我的 xpath 查询。我想用 text 搜索元素Fill color ="#C0C0C0"

etree.xpath(/node/descendant::Fill[@color='#C0C0C0'])

标签: pythonxpathlxml

解决方案


您可以简单地使用properxpath找到元素,如下所示,

In [1]: import lxml.etree as ET
In [2]: cat myxml.xml
        <node id="n25::n1">
          <data key="d5" xml:space="preserve"><![CDATA[ronin_sanity]]></data>
          <data key="d6">
            <ShapeNode>
              <Geometry height="86.25" width="182.0" x="3164.9136178770227" y="1045.403736953325"/>
              <Fill color="#C0C0C0" transparent="false"/>
              <BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
              <NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="true" width="83.376953125" x="49.3115234375" xml:space="preserve" y="33.7744140625">Messages App</NodeLabel>
              <Shape type="ellipse"/>
            </ShapeNode>
          </data>
        </node>

In [3]: tree = ET.parse('myxml.xml')

In [4]: root = tree.getroot()

In [5]: elem = root.xpath('//Fill[@color="#C0C0C0"]')

In [6]: elem
Out[6]: [<Element Fill at 0x7efe04280098>]

如果节点不匹配,那么您将得到一个空列表作为输出

In [7]: elem = root.xpath('//Fill[@color="#C0C0C0ABC"]')

In [8]: elem
Out[8]: []

推荐阅读