Find xpath tag not specified path
Is it possible to use Nokogiri::XML.xpath
or any other XML parser to find tags that are outside the specified path?
For example. If I have the following XML:
<root>
<bar>baz</bar>
<foo>
<bar>baz</bar>
</foo>
</root>
I know the bar will always exist inside foo, but it can also exist outside foo and not necessarily in the same place every time, is there a way to find this kind of conditions using xpath? I know what you can do xml.xpath("//bar")
and it will return all instances of the bar, but I need to know the parent that the bar is in.
source to share
Using:
xml.xpath('//bar[not(ancestor::foo)]')
This selects all elements bar
that are nowhere under the element foo
. (This is different from the assumption made by Dimitre, but you didn't specify it anyway)
For the provided XML document, this only selects one element: bar
under root.
source to share