how to select table column by column header name with xpath
Solution 1
Ok, i've found the answer that would suffice and look quite elegant. Here goes the required XPath string:
//table/tbody/tr/td[count(//table/thead/tr/th[.="$columnName"]/preceding-sibling::th)+1]
Put a name of the column instead of $columnName. This works well for me. There's no XSL or anything, just pure xpath string. How to apply it - it's another question.
Solution 2
If you've found a solution, I suggest posting it as an answer here, but just for fun, this is how I would approach this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:key name="kCol" match="td" use="count(. | preceding-sibling::td)"/>
<xsl:param name="column" select="'Price'" />
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<found>
<xsl:apply-templates select="table/thead/tr/th" />
</found>
</xsl:template>
<xsl:template match="th">
<xsl:if test=". = $column">
<xsl:apply-templates select="key('kCol', position())" />
</xsl:if>
</xsl:template>
</xsl:stylesheet>
When run with "Price" as the parameter value:
<found>
<td>$10</td>
<td>$20</td>
</found>
When run with "Name" as the parameter value:
<found>
<td>Premium Copier paper</td>
<td>Extra Copier paper</td>
</found>
Solution 3
You could use this XPath:
/table/tbody/tr/td[count(preceding-sibling::td)+1 = count(ancestor::table/thead/tr/th[.='Price']/preceding-sibling::th)+1]
I would think testing the position (position()
) of the td
against the position of the relevant th
would work, but it didn't seem to when I was testing.
Related videos on Youtube
![Eduard Sukharev](https://i.stack.imgur.com/DD8Ce.jpg?s=256&g=1)
Eduard Sukharev
Work as PHP Developer at eLama. Random hobbies that I hop from and to.
Updated on July 09, 2022Comments
-
Eduard Sukharev almost 2 years
I have a table of results and it looks like following:
<table> <thead> <tr> <th>Id</th> <th>Type</th> <th>Amount</th> <th>Price</th> <th>Name</th> <th>Expiration</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>Paper</td> <td>10 pcs.</td> <td>$10</td> <td>Premium Copier paper</td> <td>None</td> </tr> <tr> <td>321</td> <td>Paper</td> <td>20 pcs.</td> <td>$20</td> <td>Extra Copier paper</td> <td>None</td> </tr> </tbody>
And i want to select the whole column by its name with xpath e.g. i want the returned result to be an array of
{<td>$10</td>, <td>$20</td>}
if selected by column name "Price". I'm new to xpath and not really sure how to do this, but i'm pretty sure it's possible. -
Eduard Sukharev over 11 yearsThis seem not to work. No idea why, but i've found the solution already.
-
Daniel Haley over 11 years@EduardSukharev - You should add your solution as an answer and accept it.
-
Eduard Sukharev over 11 yearsYes, but i'm low on points so couldn't add my own solution for the first 6 hours.