Find sibling node after specified node is found
51,611
Solution 1
How can I search for a first
k
sibling afterm
node? Basically, find some node and then continue searching from that node.
Assuming that we have the following well-formed XML document:
<t>
<n></n>
<k></k>
<m></m>
<k></k>
</t>
then the following XPath expression:
/*/m[1]/following-sibling::k[1]
selects the first k
following-sibling of the first m
child of the top element of the XML document.
Solution 2
nice question : try it ........
<a>
<n></n>
<k></k>
<m></m>
<k></k> <====
<k></k>
<m></m>
<k></k>
</a>
/a/k[. = preceding::m][1]
Author by
wpfwannabe
Updated on May 31, 2020Comments
-
wpfwannabe about 4 years
Consider the following very simplified example.
<n></n> <k></k> <m></m> <k></k>
How can I search for a first
k
sibling afterm
node? Basically, find some node and then continue searching from that node. -
Nicolas Barbulesco over 10 yearsThis answer is interesting, but it starts from the first "m" having a "k" after it, not from the current node.
-
jpaugh over 8 yearsAlso, is that
preceding::m
bit a back-reference? Wouldn't that be less performant than a solution which looks form
first? (Don't know) -
Dimitre Novatchev almost 6 years@Anthony Your question is not clear. Please, provide an XML document. And why not ask a real SO question? Many people will be able to provide a good answer.
-
oldboy almost 6 yearsin other words how can i select any sibling that matches a condition?
-
Dimitre Novatchev almost 6 years@anthony:
(preceding-sibling::node()[yourCondition] | following-sibling::node()[yourCondition])[1]
This selects the first (in document order) node in the context of which yourCondition istrue()
This can be written shorter if you can use XPath 2.0 or higher -
oldboy almost 6 yearshow do i check which version of XPATH i'm using??
-
Dimitre Novatchev almost 6 yearsJust try to evaluate an XPath 2.0 expression (one that has syntax that is supported only in XPath 2.0) For example
if( 5 gt 3) then 'Greater' else 'LessOrEqual'