Home > Mobile >  XPath expression to find all previous table rows from td element
XPath expression to find all previous table rows from td element

Time:06-14

I have an HTML page that contains a table with various rows

<table>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td><strong>myTd</strong></td>
  </tr>
  <tr>
    <td></td>
  </tr>
</table>

At the moment I have an XPath to find td that contains myTd text,

/table/tbody/tr/td/strong[text()="myTd"]

but now, I need to collect all previous tr from actual td (in this example, first four tr occurrences). I tried the following XPath, but it only returns the context row (fifth tr).

/table/tbody/tr/td/strong[text()="myTd"]/ancestor::tr

CodePudding user response:

You can use this XPath-1.0 expression:

/table/tbody/tr[td/strong/text()='myTd']/preceding-sibling::tr/td

It selects the four previous td elements.

Please note that I changed "MyTd" to "myTd", because there has been a mismatch between your XML and your XPath expressions. Now the question's XML, its XPath expressions and the answer do refer to the same elements.

CodePudding user response:

This XPath,

/table/tbody/tr[td="myTd"]/preceding-sibling:tr

will select all preceding sibling tr elements before the tr element that has a td whose string value is "myTd", regardless of any strong or other wrapping markup.

  • Related