Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath query to find elements which contain a certain descendant

Tags:

xpath

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.

like image 378
Jeremy Stein Avatar asked Jul 07 '09 18:07

Jeremy Stein


People also ask

What does descendant mean in XPath?

The descendant axis indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.

What is contain in XPath?

contains() is a Selenium function that searches for web elements that contain a specific text within an Xpath expression. The XPath function contains offers the ability to detect elements containing partial text. They are used in any condition on Xpath. Lets take an HTML code here: <html>


1 Answers

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

//table[@name='important']/tr[.//interestingtag] 
like image 77
mirod Avatar answered Oct 28 '22 15:10

mirod