BanksySan
BanksySan

Reputation: 28500

XPath parent based on several children

How to I select the select the parent <tr> with the elements containing ccc and ddd in it, and no others?

i.e. from the XML below:

<table>
    <tr>
        <td>aaa</td>
        <td>bbb</td>
        <td>select</td>
    </tr>
    <tr>
        <td>ddd</td>
        <td>ccc</td>
        <td>select</td>
    </tr>
    <tr>
        <td>ccc</td>
        <td>ddd</td>
        <td>select</td>
    </tr>
    <tr>
        <td>aaa</td>
        <td>ccc</td>
        <td>select</td>
    </tr>
</table>

select this row:

<tr>
    <td>ccc</td>
    <td>ddd</td>
    <td>select</td>
</tr>

Alternatively, how do I select the third td (with select written in it) on the same row of the td's with ccc & ddd?

Upvotes: 2

Views: 62

Answers (1)

helderdarocha
helderdarocha

Reputation: 23637

An XPath expression contains several location steps. Each step creates a context either for a predicate (within [...]) or a following step. The last step contains the result set that is effectively selected. You can apply one or more predicates in any step, to reduce the set.

This expression selects the tr element which contains a td element with a string value of aaa and a td element with a string value of bbb.

//tr[td='aaa' and td='bbb']

This expression will select a set containing the two td nodes (<td>select</td>) from the second and third <tr>s (the ones that have td='ccc' and td='ddd':

//tr[td='ccc' and td='ddd']/td[3]

Instead of using and you can also stack predicates. Each predicate reduces the result set creating a context in which the following predicate operates. This has the same effect as the above expression:

//tr[td='ccc'][td='ddd']/td[3]

Upvotes: 3

Related Questions