如何使用XPath查找所有紧邻的兄弟姐妹(How to find all immediately adjacent siblings with XPath)

编程入门 行业动态 更新时间:2024-10-24 13:31:09
如何使用XPath查找所有紧邻的兄弟姐妹(How to find all immediately adjacent siblings with XPath)

我希望使用单个XPath表达式找到节点的所有紧邻的兄弟节点,如果可能的话。 鉴于输入

<a id="1"/>
<start/>
<a id="2"/>
<a id="3"/>
<b/>
<a id="4"/>
 

和一个类似于//start/following-sibling::a的XPath表达式,我想选择[2][3] ,但不是[4] 。 此外,如果starta [2]之间有任何介入元素,则不应选择任何内容。

I want to find all the immediately adjacent siblings of a node using a single XPath expression, if at all possible. Given the input

<a id="1"/>
<start/>
<a id="2"/>
<a id="3"/>
<b/>
<a id="4"/>
 

and an XPath expression similar to //start/following-sibling::a, I want to select a[2], and a[3], but not a[4]. Also, if there are any intervening elements between start and a[2], nothing should be selected.

最满意答案

我能找到的最简单的是:

//start/following-sibling::a intersect //start/following-sibling::*[name()!='a'][1]/preceding-sibling::a

这样做是:

在start : //start/following-sibling::a 。 (结果:a2,a3,a4。)现在将其设置为一侧。 然后在start : //start/following-sibling::*[name()!='a'][1] (结果:b。)之后取第一个非兄弟姐妹。 并找到它之前的所有节点: /preceding-sibling::a 。 (结果:a1,a2,a3) 取1和3的交点。(结果:a2,a3)

更新:另一种表达它的方法是//start/following-sibling::*[name()!='a'][1]/preceding-sibling::a[preceding-sibling::start] ,这大致翻译to:在start取第一个非兄弟姐妹,向后计数,但只选择仍然以start为先的元素。

更新2:如果你知道b将永远被称为b ,你当然可以用following-sibling::*[name()!='a'][1]代替替换难以阅读的following-sibling::*[name()!='a'][1]部分following-sibling::b[1] 。

The simplest one I can find was this:

//start/following-sibling::a intersect //start/following-sibling::*[name()!='a'][1]/preceding-sibling::a

What this does is:

Take all the a siblings following start: //start/following-sibling::a. (Result: a2, a3, a4.) Set this to one side for now. Then take the first non-a sibling following start: //start/following-sibling::*[name()!='a'][1] (Result: b.) And find all the a nodes that precede it: /preceding-sibling::a. (Result: a1, a2, a3) Take the intersection of 1 and 3. (Result: a2, a3)

Update: Another way to phrase it is //start/following-sibling::*[name()!='a'][1]/preceding-sibling::a[preceding-sibling::start], this roughly translates to: take the first non-a sibling following start, count backwards but only choose elements that are still preceded by start.

Update 2: If you know that b will always be called b, you can of course replace the rather hard to read following-sibling::*[name()!='a'][1] part with following-sibling::b[1].

更多推荐

XPath,start,id,<a,电脑培训,计算机培训,IT培训"/> <meta name="descript

本文发布于:2023-07-30 01:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1321399.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:紧邻   如何使用   兄弟姐妹   XPath   siblings

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!