For-each 循环中的计数器

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

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?

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

190731 次浏览

position(). E.G.:

<countNo><xsl:value-of select="position()" /></countNo>
    <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>

Try inserting <xsl:number format="1. "/><xsl:value-of select="."/><xsl:text> in the place of ???.

Note the "1. " - this is the number format. More info: here

Try:

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

Edit - had a brain freeze there, position() is more straightforward!

You can also run conditional statements on the Postion() which can be really helpful in many scenarios.

for eg.

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