Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath select descendants except nested

Tags:

nested

xpath

I want to select all "target" elements which contain somewhere a "condition" element. So far it's easy: "//target[descendant::condition]"

The problem is: My "target" elements are nested and I DON'T want to select those "target" elements in which one ore more "condition" elements is just inside another "target" element.

See, my XML looks like this

<ROOT>

<target id="1">
 <condition/>
</target>

<target id="2">
 <any_tag/>
</target>

<target id="3">
 <condition/>
 <target id="4">
   <condition>
 </target>
</target>

<target id="5">
 <target id="6">
  <condition/>
 </target>
</target>

</ROOT>

I want to select the "target" elements with the ids 1, 3, 4 and 6 but NOT 5 because between this <target> tag and the "condition" tag there is another "target" tag.

(In my real code, a "condition" element is nowhere a direct child of a "target" element. I changed that for reasons of simplifying .)

like image 274
cis Avatar asked Aug 03 '26 18:08

cis


1 Answers

You can use ancestor in this case

//condition/ancestor::target[1]

You should use [1] to select only first ancestor of each condition.

like image 187
Ievgen Avatar answered Aug 07 '26 00:08

Ievgen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!