gertvdijk
gertvdijk

Reputation: 24844

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"/>
</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.:

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

Upvotes: 162

Views: 250656

Answers (3)

s k
s k

Reputation: 5192

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.

Upvotes: 25

luis long
luis long

Reputation: 141

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

Upvotes: 14

nwellnhof
nwellnhof

Reputation: 33618

You're almost there. Simply use:

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

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

Upvotes: 233

Related Questions