How do I select child elements of any depth using XPath?


Suppose I have this (simplified):

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

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

However, my templates might change and I want to be flexible in the depth in which the submit button is located. It might be put in a table, like this:

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

I know I can select elements which are grandchildren, but I can't select grand-grand-grand-...-childeren of any depth. E.g.:

  • //form[@id='myform']/*/input[@type='submit'] only selects grand-children, no further depths.
  • //form[@id='myform']/*/*/input[@type='submit'] only selects grand-grand-children, no further or less depths.
  • //form[@id='myform']/**/input[@type='submit'] is not valid.

So, how do I select this submit button reliably without using element IDs?

This question is tagged with xpath

~ Asked on 2013-04-15 13:33:07

The Best Answer is


You're almost there. Simply use:


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

~ Answered on 2013-04-15 13:35:58


If you are using the XmlDocument and XmlNode.


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


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

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

~ Answered on 2017-01-20 02:30:30

Most Viewed Questions: