Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to select all elements with a specified name

Tags:

.net

xml

xpath

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.

like image 933
Sean Worle Avatar asked Feb 25 '13 22:02

Sean Worle


People also ask

What does * indicate in XPath?

The XPath default axis is child , so your predicate [*/android.widget.TextView[@androidXtext='Microwaves']] is equivalent to [child::*/child::android.widget.TextView[@androidXtext='Microwaves']] This predicate will select nodes with a android. widget. TextView grandchild and the specified attribute.

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.


1 Answers

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.

like image 165
nwellnhof Avatar answered Oct 09 '22 12:10

nwellnhof