Use:
(//h2[. = 'Foo bar'])[1]/following-sibling::p
[1 = count(preceding-sibling::h2[1] | (//h2[. = 'Foo bar'])[1])]
In case it is guaranteed that every h2
has a distinct value, this may be simplified to:
//h2[. = 'Foo bar']/following-sibling::p
[1 = count(preceding-sibling::h2[1] | ../h2[. = 'Foo bar'])]
This means: Select all p
elements that are following siblings of the h2
(first or only one in the document) whose string value is 'Foo bar'
and also the first preceding sibling h2
for all these p
elements is exactly the h2(first or only one in the document) whose string value is
'Foo bar'`.
Here we use a method of finding whether two nodes are identical:
count($n1 | $n2) = 1
is true()
exactly when the nodes $n1
and $n2
are the same node.
This expression can be generalized:
$x/following-sibling::p
[1 = count(preceding-sibling::node()[name() = name($x)][1] | $x)]
selects all "immediate following siblings" of any node specified by $x.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…