Search code examples
xmlxpathhtml-agility-packxpath-1.0

Find all the <tr>s which have <a> which href contains string "xxx"?


How to use xpath to get all the <tr>s which contains <a> with href containing string "xxx"?

.......
<tr><td>...</td><td><a href="xxx3" /a></td><td>...</td>......</tr> <!-- yes -->
<tr><td>...</td><td>...</td><td><a href="ab_xxx" /a></td>......</tr> <!-- yes -->
<tr><td>...</td><td>...</td><td>...</td>......</tr> <!-- no-->
.....

Solution

  • Try the xpath:

    //tr[.//a[contains(@href, 'xxx')]]
    

    A couple of notes:

    • It needs to be .//a instead of //a (note the starting period). The period says to look anywhere within the current node (ie the tr). Without the period, it looks for the anchor to be present anywhere in the document.
    • The contains method is used to check if the href attribute includes the string.