Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath Selecting all elements which doesn't have a particular element in the ancestor list

Tags:

xml

xpath

<Root>
  <SomeElement>
    ...
    <Wanted>.....</Wanted>
    <UnWanted>
      <Wanted>.....</Wanted>
    </UnWanted>
    <Wanted>.....</Wanted>
    ...
  </SomeElement>
</Root>

I want to select the "Wanted" Elements which are inside "SomeElement" at ANY level but not childs of "UnWanted" Element.

With the XPath /Root/SomeElement//Wanted I'm not able to exclude the childs of UnWanted.

like image 477
R Kaja Mohideen Avatar asked Oct 21 '22 16:10

R Kaja Mohideen


1 Answers

You could try

/Root/SomeElement//Wanted[not(ancestor::UnWanted)]

This would exclude all Wanted elements that are a child, grandchild, etc. (at any level) of an UnWanted element. If you only want to exclude Wanted elements that are a direct child of UnWanted (but still include those that are grandchildren, etc.) then change ancestor:: to parent::

/Root/SomeElement//Wanted[not(parent::UnWanted)]
like image 173
Ian Roberts Avatar answered Oct 24 '22 10:10

Ian Roberts