XPath to select all elements with a specified name

70,714

Try .//apple. This lists all the apple nodes that are descendants of the current node. For a better understanding of this topic, you should learn how XPath axes work. You could also write descendant::apple, for example.

Share:
70,714
Sean Worle
Author by

Sean Worle

Updated on June 28, 2020

Comments

  • Sean Worle
    Sean Worle about 4 years

    I believe this should be able to be answered just using standard XPath without reference to implementation, but just for reference I am using the XML DOM objects in .Net (System.Xml namespace).

    I have a node handed to my function, from somewhere deep inside an XML document, and I want to select all descendant elements of this node that have a specific name, regardless of the intervening path to those nodes. The call I'm making looks like this:

    node.SelectNodes("some XPath here");
    

    The node I'm working with looks something like this:

    ...
    <food>
      <tart>
        <apple color="yellow"/>
      </tart>
      <pie>
        <crust quality="flaky"/>
        <filling>
          <apple color="red"/>
        </filling>
      </pie>
      <apple color="green"/>
    </food>
    ...
    

    What I want is a list of all of the "apple" nodes, i.e. 3 results. I've tried a couple of different things, but none of them get what I want.

    node.SelectNodes("apple");
    

    This gives me one result, the green apple.

    node.SelectNodes("*/apple");
    

    This gives me one result, the yellow apple.

    node.SelectNodes("//apple");
    

    This gives me hundreds of results, looks like every apple node in the document, or at least maybe every apple node that is a direct child of the root of the document.

    How do I create an XPath that will give me all the apple nodes under my current node, regardless of how deep under the current node they are found? Specifically, based on my example above, I should get three results - the red, green, and yellow apples.