Jeremy Stein
Jeremy Stein

Reputation: 19661

Xpath query to find elements which contain a certain descendant

I'm using Html Agility Pack to run xpath queries on a web page. I want to find the rows in a table which contain a certain interesting element. In the example below, I want to fetch the second row.

<table name="important">
<tr>
  <td>Stuff I'm NOT interested in</td>
</tr>
<tr>
  <td>Stuff I'm interested in</td>
  <td><interestingtag/></td>
  <td>More stuff I'm interested in</td>
</tr>
<tr>
  <td>Stuff I'm NOT interested in</td>
</tr>
<tr>
  <td>Stuff I'm NOT interested in</td>
</tr>
</table>

I'm looking to do something like this:

//table[@name='important']/tr[has a descendant named interestingtag]

Except with valid xpath syntax. ;-)

I suppose I could just find the interesting element itself and then work my way up the parent chain from the node that's returned, but it seemed like there ought to be a way to do this in one step and I'm just being dense.

Upvotes: 47

Views: 41427

Answers (4)

keocra
keocra

Reputation: 633

I know it is a late answer but why not going the other way around. Finding all <interestingtag/> tags and then select the parent <tr> tag.

//interestingtag/ancestor::tr

Upvotes: 3

Tony Wickham
Tony Wickham

Reputation: 4766

I know this isn't what the OP was asking, but if you wanted to find an element that had a descendant with a particular attribute, you could do something like this:

//table[@name='important']/tr[.//*[@attr='value']]

Upvotes: 14

Scott Baker
Scott Baker

Reputation: 10443

Actually, you need to look for a descendant, not a child:

//table[@name='important']/tr[descendant::interestingtag]

Upvotes: 30

mirod
mirod

Reputation: 16161

"has a descendant named interestintag" is spelled .//interestintag in XPath, so the expression you are looking for is:

//table[@name='important']/tr[.//interestingtag]

Upvotes: 80

Related Questions