XPath Query - Select relative top level nodes
- by John
I'm trying to iterate over some elements in an XML document that may be nested, but as I iterate over them I may be removing some from the tree. I'm thinking the best way is to do this recursively, so I'm trying to come up with an XPath Query that will select all the top-level nodes relative to the current node. //foo[not(ancestor::foo)] works great at the document level, but I'm trying to figure out how to do this from a relative query.
<foo id="1">
<foo id="2" />
<foo id="3">
<foo id="4">
<bar>
<foo id="5">
<foo id="6" />
</foo>
<foo id="7" />
</bar>
</foo>
</foo>
</foo>
If the current node is foo#3, I only want to select foo#4. When the current node is foo#4, I only want to select foo#5 and foo#7.
I think I'm trying to select any descendant foo nodes of the current node, but without any ancestor foo nodes between the current node and the node I'm selecting. My conundrum is if we're already inside a foo node, not(ancestor::foo) doesn't help.