根据XPath中的列(td)获取HTML表的列名称

时间:2019-07-10 16:15:38

标签: html xslt xpath

我正在逐步浏览表中每一行的列(td),并尝试获取关联的列名,但是遇到了一些麻烦。我希望以编程方式执行此操作,因为我并不总是知道表中的列数,因此我必须在整个项目中重复多次。

编辑:由于工具要求,此版本必须为XSLT 1.0。

示例XML / HTML:

<text>
    <table>
        <thead>
            <tr>
                <th>Allergy Name</th>
                <th>Reaction Description</th>
                <th>Start Date</th>
                <th>Severity</th>
                <th>Status</th>
                <th>Provider</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>MUCINEX D</td>
                <td>Hallucinations</td>
                <td>2015/11/19</td>
                <td>Critical</td>
                <td>Active</td>
                <td>Mickey Mouse, MD</td>
            </tr>
        </tbody>
    </table>
</text>

XSLT代码段:

<xsl:for-each select="tr">
<!-Getting other data here-->
   <xsl:for-each select="td">
            <xsl:value-of select="~COLUMN NAME~"/> <!--Looking for the column name here-->
   </xsl:for-each>
</xsl:for-each>

理想情况下,我会得到类似的东西:

Allergy Name: MUCINEX D

,依此类推,遍历表中的每一列。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下XSLT-1.0代码。当然,您必须调整一些实际文件布局的路径。

<xsl:for-each select="table/tbody/tr">
    <!-- Getting other data here-->
    <xsl:for-each select="td">
        <xsl:variable name="pos" select="position()" />
        <xsl:value-of select="../../../thead/tr/th[$pos]"/> <!--Looking for the column name here-->
        <xsl:value-of select="concat(': ',.)"/>
        <xsl:text>&#xa;</xsl:text>
    </xsl:for-each>
</xsl:for-each>

变量将当前位置保存在td元素集中,并将其用作th元素的索引。 th元素是通过相对路径访问的;绝对路径可能会更好,但这取决于文件布局以及您要处理多个表还是仅处理一个表。

其输出为:

Allergy Name: MUCINEX D
Reaction Description: Hallucinations
Start Date: 2015/11/19
Severity: Critical
Status: Active
Provider: Mickey Mouse, MD

或者,您也可以通过小技巧使用xsl:key。可能这会更快,但使用多个表会感到不舒服。

但是,这是样式表的外观:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" indent="no" />
    <xsl:key name="hdr" match="tr/th" use="count(preceding-sibling::th) + 1" />

    <xsl:template match="/text">
        <xsl:for-each select="table/tbody/tr">
            <!-- Getting other data here-->
            <xsl:for-each select="td">
                <xsl:value-of select="key('hdr',position())" /> 
                <xsl:value-of select="concat(': ',.)"/>
                <xsl:text>&#xa;</xsl:text>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

输出是相同的。

相关问题