92

如何在 xsl:for-each 循环中获取一个计数器,以反映当前处理的元素数量。
例如我的源 XML 是

<books>
    <book>
        <title>The Unbearable Lightness of Being </title>
    </book>
    <book>
        <title>Narcissus and Goldmund</title>
    </book>
    <book>
        <title>Choke</title>
    </book>
</books>

我想要得到的是:

<newBooks>
    <newBook>
        <countNo>1</countNo>
        <title>The Unbearable Lightness of Being </title>
    </newBook>
    <newBook>
        <countNo>2</countNo>
        <title>Narcissus and Goldmund</title>
    </newBook>
    <newBook>
        <countNo>3</countNo>
        <title>Choke</title>
    </newBook>
</newBooks>

要修改的 XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <newBooks>
            <xsl:for-each select="books/book">
                <newBook>
                    <countNo>???</countNo>
                    <title>
                        <xsl:value-of select="title"/>
                    </title>
                </newBook>
            </xsl:for-each>
        </newBooks>
    </xsl:template>
</xsl:stylesheet>

所以问题是用什么代替???。是否有任何标准关键字或者我只是必须声明一个变量并在循环内递增它?

由于问题很长,我可能应该期待一行或一个单词的答案:)

4

5 回答 5

148

position(). 例如:

<countNo><xsl:value-of select="position()" /></countNo>
于 2008-09-18T15:25:19.063 回答
13

尝试<xsl:number format="1. "/><xsl:value-of select="."/><xsl:text>在 ??? 的位置插入。

注意“1.” - 这是数字格式。更多信息:这里

于 2008-09-18T15:26:27.687 回答
10

尝试:

<xsl:value-of select="count(preceding-sibling::*) + 1" />

编辑- 在那里大脑冻结, position() 更直接!

于 2008-09-18T15:28:11.723 回答
8

您还可以在 Postion() 上运行条件语句,这在许多情况下都非常有用。

例如。

 <xsl:if test="(position( )) = 1">
     //Show header only once
    </xsl:if>
于 2010-11-20T01:05:46.900 回答
5
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <newBooks>
                <xsl:for-each select="books/book">
                        <newBook>
                                <countNo><xsl:value-of select="position()"/></countNo>
                                <title>
                                        <xsl:value-of select="title"/>
                                </title>
                        </newBook>
                </xsl:for-each>
        </newBooks>
    </xsl:template>
</xsl:stylesheet>
于 2008-09-18T15:26:25.627 回答