XPath 选择多个子项中//和/descendant 之间的差异 [英] Differences between // and /descendant in XPath selecting multiple children

查看:96
本文介绍了XPath 选择多个子项中//和/descendant 之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 XPath 中选择基本元素的多个子元素时,我无法清楚地理解使用 //element/descendant::element 之间的区别.

给定这个 HTML 片段

<身体><div class="popupContent"><表格><tr class="aclass"><td>你好</td><td><input type="text" value="FIRST"/></td></tr><tr class="aclass"><td>再见</td><td><input type="text" value="SECOND"/></td></tr>

</html>

我需要根据每个 input 在表格中的位置来选择它.//div[@class='popupContent']//input[1] 这里选择第一个输入//div[@class='popupContent']//input[2] 这给出了错误//div[@class='popupContent']/descendant::input[1] 再次选择第一个输入//div[@class='popupContent']/descendant::input[2] 这里选择第二个输入

使用 /descendant::input 可以满足我的需求:获取所有输入并让我按位置选择.
// 有何不同?为什么它只返回第一个元素而不返回后面的元素?

我知道另一个问题 但答案基本上说它们是别名并指向文档,我无法理解并且缺乏具体示例.与该问题的不同之处在于我需要选择多个子元素,而 // 不允许这样做.

解决方案

//X/descendant::X 之间的唯一区别是当 X 包含一个位置谓词,例如 //x[1]/descendant::x[1].在这种情况下,//x[1] 选择作为其父元素的第一个 x 子元素的每个 x 元素,而 /后代::x[1] 选择第一个后代 x 整体.你可以通过记住 //x[1]/descendant-or-self::node()/child::x[1] 的缩写来解决这个问题

I can't clearly understand the differences between using //element and /descendant::element when selecting multiple children of a base element in XPath.

Given this HTML snippet

<html>
<body>
<div class="popupContent">
  <table>
    <tr class="aclass"><td> Hello </td> <td> <input type="text" value="FIRST" /> </td></tr>
    <tr class="aclass"><td> Goodbye </td> <td> <input type="text" value="SECOND" /> </td></tr>
  </table>
</div>
</body>
</html>

I need to select each input based on its positioning in the table. //div[@class='popupContent']//input[1] this selects the first input //div[@class='popupContent']//input[2] this gives error //div[@class='popupContent']/descendant::input[1] this again selects the first input //div[@class='popupContent']/descendant::input[2] this select the second input

Using /descendant::input does what I need: grab all inputs and let me select by position.
How does // differ? Why does it return only the first element and not the ones after?

I'm aware of this other question but the answer basically says they're aliases and point to the documentation, which I cannot understand and lacks a concrete example. Difference with that question is that my need is to select multiple children elements, and // doesn't allow it.

解决方案

The only difference between //X and /descendant::X is when X contains a positional predicate, for example //x[1] vs /descendant::x[1]. In this situation //x[1] selects every x element that is the first x child of its parent element, whereas /descendant::x[1] selects the first descendant x overall. You can work this out by remembering that //x[1] is short for /descendant-or-self::node()/child::x[1]

这篇关于XPath 选择多个子项中//和/descendant 之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆