how to select table column by column header name with xpath

后端 未结 3 1084
礼貌的吻别
礼貌的吻别 2021-02-05 18:57

I have a table of results and it looks like following:

Id&
相关标签:
3条回答
  • 2021-02-05 19:18

    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.

    0 讨论(0)
  • 2021-02-05 19:23

    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>
    
    0 讨论(0)
  • 2021-02-05 19:24

    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.

    0 讨论(0)
提交回复
热议问题