xsl:for-each循环内的计数器
时间:2020-03-06 14:21:52 来源:igfitidea点击:
如何在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>
因此,问题是用什么代替???。是否有任何标准关键字,还是我必须简单地声明一个变量并在循环内将其递增?
由于问题很长,我可能应该期待一行或者一个单词的答案:)
解决方案
position()
。例如。:
<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>
尝试在???位置插入
<xsl:number format =" 1. " /> <xsl:value-of select ="。" /> <xsl:text>`。
请注意"1. "这是数字格式。更多信息:这里
尝试:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit在那里冻结了大脑,position()更简单了!
我们还可以在Postion()上运行条件语句,这在许多情况下都非常有用。
例如
<xsl:if test="(position( )) = 1"> //Show header only once </xsl:if>