How to select children of any depth using XPath?

Suppose I have this (simplified):

<form id="myform"> <!-- some input fields --> <input type="submit" value="proceed"/> </form> 

Then I can select the XPath submit button //form[@id='myform']/input[@type='submit'] . Fine.

However, my templates can change, and I want to be flexible in the depth in which the submit button is located. It can be placed in a table, for example:

 <form id="myform"> <!-- some input fields --> <table><tr><td> <input type="submit" value="proceed"/> </td></tr></table> </form> 

I know that I can choose elements that are grandchildren, but I cannot choose grand grand grand ... any depth. For example:.

  • //form[@id='myform']/*/input[@type='submit'] selects only grand children, further depths.
  • //form[@id='myform']/*/*/input[@type='submit'] selects only grand-grand-children, without further or lesser depths.
  • //form[@id='myform']/**/input[@type='submit'] invalid.

So, how can I select this submit button correctly without using item identifiers?

+49
xpath
Apr 15 '13 at 13:33
source share
3 answers

You are almost there. Just use:

 //form[@id='myform']//input[@type='submit'] 

The // label can also be used inside an expression.

+80
Apr 15 '13 at 13:35
source share

If you are using XmlDocument and XmlNode.

Say:

 XmlNode f = root.SelectSingleNode("//form[@id='myform']"); 

Using:

 XmlNode s = f.SelectSingleNode(".//input[@type='submit']"); 

It depends on the tool you use. But .// any child, any depth will select from the node link.

+5
Jan 20 '17 at 2:30
source share
 //form/descendant::input[@type='submit'] 
+4
Jul 01 '16 at 3:12
source share



All Articles