简体   繁体   中英

Find xpath tag not in specified path

Is it possible using Nokogiri::XML.xpath , or any other XML parser to find tags that are outside the specified path?

For instance. If I have the following XML:

<root>
  <bar>baz</bar>
  <foo>
    <bar>baz</bar>
  </foo>
</root>

I know that bar will always exist inside of foo, but it may also exist outside of foo, and not necessarily in the same place everytime, is there a way to search for that kind of condition with xpath? I know you can do xml.xpath("//bar") and it will return all instances of bar, but I need to be able to know the parent object that bar exists in.

Use:

xml.xpath('//bar[not(ancestor::foo)]')

This selects all bar elements that are not anywhere under a foo element. (This is different than the assumption Dimitre made, but you haven't specified either way)

For the provided XML document, this selects just one element: the bar under root.

Use :

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

This selects all elements in the XML document that are not foo and that have a child bar .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM