如何使用 XSLT 2.0 在 XML 文档中找到第一个 table

How to find first table in XML document using XSLT 2.0

我想在 xml 文档中找到第一个 table。我在下面提到了例子。

输入

<doc>
    <first>
        <table-cover>
            <table>
                <thead>Table1</thead>
                <tbody>Table1</tbody>
            </table>
        </table-cover>
    </first>
    <first>
        <second>
            <table-cover>
                <table>
                    <thead>Table2</thead>
                    <tbody>Table2</tbody>
                </table>
        </table-cover>
        </second>
    </first>
    <first>
        <table-cover>
            <table>
                <thead>Table3</thead>
                <tbody>Table3</tbody>
            </table>
        </table-cover>
    </first>
</doc>

我想为文档中的第一个 table 添加名为 <first-table> 的特殊元素

尝试过的模板:

<xsl:template match="table-cover">
    <xsl:choose>
        <xsl:when test="table/position() eq 1">
            <!-- code -->
        </xsl:when>
        <xsl:otherwise>
            <!-- code -->
        </xsl:otherwise>
    <xsl:choose>
</xsl:template>

但是当我使用上面的模板时,所有 table 都被选中并为所有 table 应用条件。我只想将 <xsl:when test="table/position() eq 1"> 应用于第一个 table。

如何通过更改 <xsl:when test="??????">

来解决这个问题

我正在使用 XSLT 2.0。谢谢

您可以使用

测试table是否是文档中的第一个table
test="empty(table/preceding::table)"

我会在这里使用两个模板规则,而不是 xsl:choose。

如果文档很大,那么测试每个 table 以查看是否有更早的 table 是低效的。更快的方法是将全局变量绑定到第一个 table:

<xsl:variable name="first-table" select="(//table)[1]"/>

然后针对此变量测试后续 tables:

<xsl:template match="table[. is $first-table]">...