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:



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

2 answers




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.




//*[not(self::foo) and bar]


This selects all elements in the XML document that are not foo

and have a child bar


For the provided XML document, this only selects one element - root




All Articles