我希望使用单个XPath表达式找到节点的所有紧邻的兄弟节点,如果可能的话。 鉴于输入
<a id="1"/> <start/> <a id="2"/> <a id="3"/> <b/> <a id="4"/>和一个类似于//start/following-sibling::a的XPath表达式,我想选择[2]和[3] ,但不是[4] 。 此外,如果start和a [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::aWhat 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
发布评论