python - 如何使用 XPath 通过其同级节点的属性来发现 XML 节点?

标签 python xml python-3.x xpath elementtree

假设我有以下 XML 文件(可有可无的部分标有“...”):

<?xml version="1.0" encoding="ISO-8859-1"?>
<PARAMETERS version="1.6.2" xsi:noNamespaceSchemaLocation="http://open-ms.sourceforge.net/schemas/Param_1_6_2.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <NODE name="info" description="">
    <ITEM name="version" value="2.0.0" type="string" description="" required="false" advanced="false" />
    <ITEM name="num_vertices" value="5" type="int" description="" required="false" advanced="false" />
    <ITEM name="num_edges" value="4" type="int" description="" required="false" advanced="false" />
    <ITEM name="description" value="&lt;![CDATA[]]&gt;" type="string" description="" required="false" advanced="false" />
  </NODE>
  <NODE name="vertices" description="">
    <NODE name="0" description="">
      <ITEM name="recycle_output" value="false" type="string" description="" required="false" advanced="false" />
      <ITEM name="toppas_type" value="input file list" type="string" description="" required="false" advanced="false" />
      <ITEMLIST name="file_names" type="string" description="" required="false" advanced="false">
        <LISTITEM value="input_data/STD_MIX_1_25_neg.mzML"/>
      </ITEMLIST>
      <ITEM name="x_pos" value="-1680" type="double" description="" required="false" advanced="false" />
      <ITEM name="y_pos" value="-620" type="double" description="" required="false" advanced="false" />
    </NODE>
    <NODE name="1" description="">
    ...
    </NODE>
    ...
  </NODE>
</PARAMETERS>

我的目标是进行一个 XPath 查询,返回具有属性 name="file_names"的 ITEMLIST 节点和具有属性 name="toppas_type"、value="input file list"的同级 ITEM 节点。我尝试了以下一种:

'./NODE/NODE[ITEM[@name="toppas_type"][@value="输入文件列表"]]/ITEMLIST[@name="file_names"]'

在 Python 3.4 中使用 xml.etree.ElementTree,但出现错误“谓词无效”。我认为我的查询包含一个愚蠢的错误,但我找不到它。

最佳答案

xml.etree.ElementTree 有一个 limited XPath support :

This module provides limited support for XPath expressions for locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module.

如果您可以切换到 lxml ,可以用 following-sibling 来解决轴:

//ITEM[@name = 'toppas_type' and @value = 'input file list']/following-sibling::ITEMLIST[@name = 'file_names']

关于python - 如何使用 XPath 通过其同级节点的属性来发现 XML 节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32443827/

相关文章:

java - Android相对布局问题

python - 如何处理线程模块中引发的 KeyboardException?

python - 在 tkinter 中如何将入口函数分配给变量

python - 将多列的行反转为垂直连接的列

python 请求 'certificate verify failed' 获取特定的 SNI 证书

php - 将xml数据导入mysql,如何管理对文件的修改

android - SAXParser 有时会返回一个错误的值

python - 如何在kivy启动时使用触摸屏?

python - 'numpy.reshape' 和 'ndarray.reshape' 如何等效?

python - 按日期对对象列表进行排序,其中对象没有名称