Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath Select Nodes where all parent nodes do not contain specific attribute and value

Tags:

xpath

I have the following XML structure:

<root>
  <Level1 IsEnabled="0"> <!-- Disabled -->
    <Level2 IsEnabled="1">
      <Level3 IsEnabled="1">
        <Level4 IsEnabled="1">
          <Child /> <!-- Don't include this one -->
        </Level4>
      </Level3>
    </Level2>
  </Level1>
  <Level1 IsEnabled="1">
    <Level2 IsEnabled="1">
      <Level3 IsEnabled="0"> <!-- Disabled -->
        <Level4 IsEnabled="1">
          <Child /> <!-- Don't include this one -->
        </Level4>
      </Level3>
    </Level2>
  </Level1>
  <Level1 IsEnabled="1">
    <Level2 IsEnabled="1">
      <Level3 IsEnabled="1">
        <Level4 IsEnabled="1">
          <Child /><!-- Include this one -->
        </Level4>
      </Level3>
    </Level2>
   </Level1>
</root>

I want to select all child nodes where any of its ancestors do not contain IsEnabled="0". So for the XML above I only want to select the last child node. In addition, if a ancestor node doesn't contain a IsEnabled attribute, then the child should still be included.

like image 605
Matt Ruwe Avatar asked Jun 19 '13 13:06

Matt Ruwe


People also ask

How do you access the parent of a node with XPath?

A Parent of a context node is selected Flat element. A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.

How do I select all child elements in XPath?

For the div element with an id attribute of hero //div[@id='hero'] , these XPath expression will select elements as follows: //div[@id='hero']/* will select all of its children elements. //div[@id='hero']/img will select all of its children img elements. //div[@id='hero']//* will select all of its descendent elements.

What is an ancestor node in XPath?

Definition of XPath Ancestor. The ancestor axis chooses all of the current node's ancestor elements (parent, grandparent, great-grandparents, and so on). The root node is always present on this axis (unless the current node is the root node).


1 Answers

Q: I want to select all child nodes where any of its ancestors do not contain IsEnabled="0" Try this:

//Child[not(ancestor::*[@IsEnabled='0'])]
like image 115
hr_117 Avatar answered Dec 31 '22 18:12

hr_117