本文介绍了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 循环中的计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:47