Darth
Darth

Reputation: 229

Using xpath - How to select column data related to table header

<table border="1">
    <tbody>
        <tr>
            <th>ID</th>
            <th>Product</th>
            <th>Color</th>
            <th>Model</th>
        </tr>
        <tr>
            <td>22</td>
            <td>Car</td>
            <td>blue</td>
            <td>
                <ul>
                </ul>
            </td>
        </tr>
    </tbody>
</table>

Above is a snippet of a highly nested html document. To get the table level I have used the following xpath

//th[contains(text(), "ref_code")]/following-
sibling::td[contains(text(), "197")]/ancestor::table[2]

How then can I edit the same xpath and select a specific table header data and the corresponding table data column like so using xpath:

ID |Product |Color

22 |Car |Blue

Any help will be appreciated

Upvotes: 2

Views: 8022

Answers (2)

SomeDude
SomeDude

Reputation: 14238

From your comments to the answers given here: I assume that you get the above table from an existing xpath which is :

//th[contains(text(), "ref_code")]/following-
sibling::td[contains(text(), "197")]/ancestor::table[2]

Now you want to add/edit to this xpath such that you get the values of td given a column for e.g. Color, then the below xpath should give you the td values for all columns given Color as input:

//td[position()<=(count(//tr/th[.='Color']/preceding-sibling::*)+1) ]

Assuming your first xpath works correctly, add the above xpath to that like:

//th[contains(text(), "ref_code")]/following-
sibling::td[contains(text(), "197")]/ancestor::table[2]//td[position()<=(count(//tr/th[.='Color']/preceding-sibling::*)+1) ]

Output:

<td>22</td>
<td>Car</td>
<td>blue</td>

If you want just the Color, use xpath :

//td[(count(//tr/th[.='Color']/preceding-sibling::*)+1) ]

If you want just the Product use xpath :

//td[(count(//tr/th[.='Product']/preceding-sibling::*)+1) ]

If you want just the ID use xpath :

//td[(count(//tr/th[.='ID']/preceding-sibling::*)+1) ]

Note that the xpath changes at th[.='XXX'] where XXX is the selected element.

But if you want the output to be in the form of a table , you need to use XSLT, because you are trying to get a transformed view of your html , not just selected elements.

Upvotes: 5

Vitaliy Moskalyuk
Vitaliy Moskalyuk

Reputation: 2583

We seach for table data //table//td by position in header of column //table//th[text()='Color']

That [count(element/preceding-sibling::*) +1] is how to find element's index

So result is:

//table//td[count(//table//th[text()='Color']/preceding-sibling::*) +1]

Upvotes: 0

Related Questions