Mukund
Mukund

Reputation: 946

How to select table entry via XPath

I have the following table, and I wanted an expression to get the Percentage of the Category "OC". Is it possible to extract via XPath?

<tbody>
  <tr>
    <th class="textL">Category</th>
    <th class="textR">No. of Items</th>
    <th class="textR">Percentage</th>
  </tr>
  <tr class="data_row">
    <td>OC</td>
    <td class="textR">100</td>
    <td class="textR">4.70</td>
  </tr>
  <tr class="data_row">
    <td>FP</td>
    <td class="textR">200</td>
    <td class="textR">38.82</td>
  </tr>
  <tr class="data_row">
    <td>FI</td>
    <td class="textR">300</td>
    <td class="textR">20.39</td>
  </tr>
</tbody>

Upvotes: 1

Views: 882

Answers (4)

user2314737
user2314737

Reputation: 29317

Another XPath, also dependent on the order of the table's columns

//td[text()='OC']/following-sibling::td[2]

(explanation: take the second td sibling among the siblings of a td that contains text 'OC')

Upvotes: 1

StuBob
StuBob

Reputation: 1598

This works:

tbody/tr/td[. eq "OC"]/../td[@class eq "textR"][2]/text()

It assumes that the OC td element will be there, and that the value you want is the 2nd element with a "textR" attribute.

Upvotes: 0

kjhughes
kjhughes

Reputation: 111531

Selecting table entry based on value of another entry

To select the Percentage for the given "OC" Category:

//td[.='OC']/following-sibling::td[count(../..//th[.='Percentage']/preceding-sibling::th)]/text()

The above XPath will return

"4.70"

as requested.

Note that it will continue to work in the face of many changes, including row and column rearrangements as long as the targeted column continues to be named "Percentage" and remains after the Category column in the first column. One could even further generalize the expression by taking the difference of the positions of the two columns rather than assuming that Category is the first column.

Explanation: From the td that contains "OC", go over the number of siblings equal to the position of the "Percentage" column header, and there select the text in the correct sibling td.

Upvotes: 3

Juan
Juan

Reputation: 3705

There are multiple XPaths for that. This one will work:

/tbody[1]/tr[2]/td[3]/text()

But it is based on the current layout of the XML

Upvotes: 0

Related Questions