tags:

views:

363

answers:

2

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.

+3  A: 

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

//table[@name='important']/tr[.//interestingtag]
mirod
That works. Thanks!
Jeremy Stein
+5  A: 

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

//table[@name='important']/tr[descendant::interestingtag]
ScottSEA
or, @mirod's way would work too. :-)
ScottSEA
Excellent. That's very helpful. Sorry I can't accept two answers!
Jeremy Stein
I always find it fun how many ways there are to get the desired result in XPath. I believe //table[@name='important']//interestingtag//ancestor::tr should work too I believe.
mirod
ScottSEA
+1 for using the "descendant" axis. More readable than the ".//" shorthand, IMHO.
Tomalak
@Tomalak: you're too kind. :-) I find it more readable as well... too easy to misplace or not see the period, IMHO.
ScottSEA
+1 from me too, I am used to the ".//" form, but I also do Perl for a living ;--) so "descendant::" is probably clearer.
mirod