【问题标题】:how to select table column by column header name with xpath如何使用xpath按列标题名称选择表列
【发布时间】:2013-02-07 07:03:21
【问题描述】:

我有一个结果表,如下所示:

<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>

我想用 xpath 选择整个列的名称,例如如果按列名“价格”选择,我希望返回的结果是{&lt;td&gt;$10&lt;/td&gt;, &lt;td&gt;$20&lt;/td&gt;} 的数组。 我是 xpath 的新手,不太确定如何执行此操作,但我很确定这是可能的。

【问题讨论】:

    标签: select xpath


    【解决方案1】:

    好的,我找到了足够的答案并且看起来很优雅。这是所需的 XPath 字符串:

    //table/tbody/tr/td[count(//table/thead/tr/th[.="$columnName"]/preceding-sibling::th)+1]
    

    用列名代替 $columnName。这对我很有效。没有 XSL 或任何东西,只有纯 xpath 字符串。如何应用它 - 这是另一个问题。

    【讨论】:

      【解决方案2】:

      你可以使用这个 XPath:

      /table/tbody/tr/td[count(preceding-sibling::td)+1 = count(ancestor::table/thead/tr/th[.='Price']/preceding-sibling::th)+1]
      

      我认为根据相关 th 的位置测试 td 的位置 (position()) 会起作用,但在我测试时似乎没有。

      【讨论】:

      • 这似乎不起作用。不知道为什么,但我已经找到了解决方案。
      • @EduardSukharev - 您应该添加您的解决方案作为答案并接受它。
      • 是的,但我的分数很低,所以前 6 个小时无法添加我自己的解决方案。
      【解决方案3】:

      如果您找到了解决方案,我建议将其作为答案发布在这里,但只是为了好玩,这就是我的处理方式:

      <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>
      

      以“价格”作为参数值运行时:

      <found>
        <td>$10</td>
        <td>$20</td>
      </found>
      

      以“名称”作为参数值运行时:

      <found>
        <td>Premium Copier paper</td>
        <td>Extra Copier paper</td>
      </found>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-31
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        相关资源
        最近更新 更多