计数器内部xsl:for-each循环

时间:2008-09-18 15:19:44

标签: xml xslt loops

如何在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>

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

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

5 个答案:

答案 0 :(得分:134)

position()。 E.G:

<countNo><xsl:value-of select="position()" /></countNo>

答案 1 :(得分:13)

尝试在???。

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

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

答案 2 :(得分:7)

尝试:

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

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

答案 3 :(得分:7)

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

例如。

 <xsl:if test="(position( )) = 1">
     //Show header only once
    </xsl:if>

答案 4 :(得分: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>