【问题标题】:Find XML node with a specific child using GPath使用 GPath 查找具有特定子节点的 XML 节点
【发布时间】:2019-06-11 13:37:15
【问题描述】:

我正在寻找一个 GPath 表达式来查找具有特定子节点的节点。

<table>
   <tr>
      <td name="line">1</td>
      <td name="price">10</td>
   </tr>
   <tr>
      <td name="line">2</td>
      <td name="price">95</td>
   </tr>
   <tr>
      <td name="line">3</td>
      <td name="price">43</td>
   </tr>
</table>

在上面的示例 XML 中,我想检索整个 tr 元素,该元素包含一个 td 元素,其属性为 price 和文本 95

在 XPath 中我会这样写:

//tr[td[@name='price' and text()='95']]

我尝试过的代码看起来像这样......

xmlDoc.tr.td.find { node -> node.text() == '1' }.parent()

...但这更像是他的 XPath 等价物:

//tr/td[@name='price' and .='95']/parent::*

在这个确切的场景中它会做,但我不是父斧的忠实粉丝。假设会有更多的子节点级别,我将如何处理“嵌套”谓词?返回一个有子节点的节点...?

非常感谢!

【问题讨论】:

    标签: xml xpath groovy gpath


    【解决方案1】:

    您可以使用tr 作为查找的根,并使用深度优先属性** 来搜索整个子树

    xmlDoc.tr.find { tr -> tr.'**'.find { it.name() == 'td' && it.text() == '1' } }
    

    【讨论】:

    • 正是我想要的,非常感谢。
    猜你喜欢
    • 2011-01-13
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多