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

Xpath

Xpath Problem Overview


Suppose I have this (simplified):

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

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 -->
    <table><tr><td>
           <input type="submit" value="proceed"/>
    </td></tr></table>
</form>

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?

Xpath Solutions


Solution 1 - Xpath

You're almost there. Simply use:

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

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

Solution 2 - Xpath

If you are using the XmlDocument and XmlNode.

Say:

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

Use:

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.

Solution 3 - Xpath

//form/descendant::input[@type='submit']

Solution 4 - Xpath

Also, you can do it with css selectors:

form#myform input[type='submit']

space beween elements in css elector means searching input[type='submit'] that elements at any depth of parent form#myform element

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongertvdijkView Question on Stackoverflow
Solution 1 - XpathnwellnhofView Answer on Stackoverflow
Solution 2 - Xpaths kView Answer on Stackoverflow
Solution 3 - Xpathluis longView Answer on Stackoverflow
Solution 4 - XpathMahsum AkbasView Answer on Stackoverflow