python - 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'])
解决方案
您可以简单地使用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]: []
推荐阅读
- laravel - Vagrant:多盒 laravel/宅基地。如何通过 macOS 命令行删除旧的?
- c# - join 子句中表达式之一的类型不正确 type interface failed in call to join
- regex - 如果字符串第一次出现点,则正则表达式匹配?
- pyspark - AWS EMR 中的 Spark 步骤因 exitCode 13 而失败
- android - 从另一个活动 onBackPressed 完成活动
- ruby-on-rails - 未定义的方法 'e=' 用于#
- c# - 如何在 Xamarin Android 上使用 C# 在 Document Start 处注入 Javascript
- python - 如何在多标签分类问题中处理 JSON 文件?
- r - R - 为 colorRampPalette 中的最小值分配特殊颜色
- jdbc - 如何从 DataSource 或 Connection 对象中获取模式名称