lxml错误:lxml.etree.XPathEvalError:带有后代的无效表达式

时间:2018-12-04 07:22:40

标签: python xpath lxml

由于我也是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查询。我想用文本Fill color ="#C0C0C0"搜索元素。

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

1 个答案:

答案 0 :(得分:0)

您可以简单地使用适当的xpath来查找元素,如下所示,

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]: []