xml - xsl :for-each loop 内的计数器

标签 xml xslt loops

如何在 xsl:for-each 循环中获取一个计数器,以反射(reflect)当前处理的元素的数量。
例如我的源 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>

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

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

最佳答案

位置()。例如:

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

关于xml - xsl :for-each loop 内的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/93511/

相关文章:

iphone - 如何使用苹果的 KML 查看器示例代码显示多边形

xml - 如何通过分层节点与 XSLT 循环?

java - XSL 的后处理步骤

c - 如何在循环的最后停止换行?

c# - 如何以编程方式从类型生成 xml 架构?

android - 更新的 SDK 管理器导致大量错误

xml - 如何在 bash 中使用 xmlstarlet 选择随机节点?

php - 使用 text() 匹配 XSLT 中的自定义实体名称

scala - 为什么在未指定参数名称时 foreach 只执行一次?

python - 在没有字符串切片的情况下打印字符串中的奇数字符?