2

I'm new to XPATH and I'd like to know if there is a nice way to do this using XPATH queries.

I want to match consecutive sibling nodes in a XML tree to certain predefined rules for example if there are three sibling nodes occurring immediately one after the other and they have the attributes value="A", value="B" and value="C", I want the XPATH query to match the first node/last node in such a sequence and I want to extract all such consecutive sequence of nodes from the XML tree so that I can process them later on.

Thanks!

2 Answers2

3

Here is one possible solution:

First:

I want to match consecutive sibling nodes in a XML tree to certain predefined rules for example if there are three sibling nodes occurring immediately one after the other and they have the attributes value="A", value="B" and value="C",

//*[@value='A' 
  and 
   following-sibling::*[1]/@value='B' 
  and 
   following-sibling::*[2]/@value='C']

Then:

I want to extract all such consecutive sequence of nodes from the XML tree ...

    //*[@value='A' 
      and 
       following-sibling::*[1]/@value='B' 
      and 
       following-sibling::*[2]/@value='C']
   |
    //*[@value='A' 
      and 
       following-sibling::*[1]/@value='B' 
      and 
       following-sibling::*[2]/@value='C']

      /following-sibling::*[position() = 1 or position()=2]

Here is how the selection looks like in the true XPathVisualizer (_http://www.topxml.com/xpathvisualizer/ -- this link has a trojan -- click only if you have good malware protection. Alternatively, contact me for the app.):

alt text

Finally:

I want the XPATH query to match the first node/last node in such a sequence

    //*[@value='A' 
      and 
       following-sibling::*[1]/@value='B' 
      and 
       following-sibling::*[2]/@value='C']
   |
    //*[@value='A' 
      and 
       following-sibling::*[1]/@value='B' 
      and 
       following-sibling::*[2]/@value='C']

      /following-sibling::*[position()=2]
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
1

Note: This doesn't answer the question. I misunderstood it when writing this.

To query them, use position()=1 or position()=last() as a predicate, possibly along with other predicates you use to select the nodes.

This is what it looks like in XpathVisualizer:

alt text

"Extracting them" is not a matter for xpath. For that you can enumerate the selected elements and then do whatever you like, it's up to you.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Cheeso
  • 189,189
  • 101
  • 473
  • 713