开发者

Xpath Query to match immediate sibling nodes in a sequence

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!


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.):

Xpath Query to match immediate sibling nodes in a sequence

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]


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:

Xpath Query to match immediate sibling nodes in a sequence

"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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜