我正在寻找一个 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::*
在这种确切的情况下它会做,但我不是父斧头的忠实粉丝。假设会有更多的子节点级别,我将如何处理“嵌套”谓词?返回一个节点,它有一个有孩子的孩子......?
非常感谢!
您可以将tr
用作查找的根,并使用深度优先属性**
来搜索整个子树
xmlDoc.tr.find { tr -> tr.'**'.find { it.name() == 'td' && it.text() == '1' } }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句