Find sibling node after specified node is found

51,611

Solution 1

How can I search for a first k sibling after m 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]
Share:
51,611
wpfwannabe
Author by

wpfwannabe

Updated on May 31, 2020

Comments

  • wpfwannabe
    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 after m node? Basically, find some node and then continue searching from that node.

  • Nicolas Barbulesco
    Nicolas Barbulesco over 10 years
    This answer is interesting, but it starts from the first "m" having a "k" after it, not from the current node.
  • jpaugh
    jpaugh over 8 years
    Also, is that preceding::m bit a back-reference? Wouldn't that be less performant than a solution which looks for m first? (Don't know)
  • Dimitre Novatchev
    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
    oldboy almost 6 years
    in other words how can i select any sibling that matches a condition?
  • Dimitre Novatchev
    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 is true() This can be written shorter if you can use XPath 2.0 or higher
  • oldboy
    oldboy almost 6 years
    how do i check which version of XPATH i'm using??
  • Dimitre Novatchev
    Dimitre Novatchev almost 6 years
    Just 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'