xsl:for-each循环内的计数器 [英] Counter inside xsl:for-each loop

查看:427
本文介绍了xsl:for-each循环内的计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to get a counter inside xsl:for-each loop that would reflect the number of current element processed.
For example my source XML is

<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>

所以问题是用什么代替???.是否有任何标准关键字,还是我必须简单地声明一个变量并在循环内将其递增?

So the question is what to put in place of ???. Is there any standard keyword or do I simply must declare a variable and increment it inside the loop?

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

As the question is pretty long I should probably expect one line or one word answer :)

推荐答案

position().例如:

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

这篇关于xsl:for-each循环内的计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆