xml xsl:for-each 循环中的计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/93511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counter inside xsl:for-each loop
提问by kristof
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
如何在 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>
What I want to get is:
我想得到的是:
<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>
The XSLT to modify:
要修改的 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 :)
由于问题很长,我可能应该期待一行或一个词的答案:)
回答by redsquare
position(). E.G.:
position(). 例如:
<countNo><xsl:value-of select="position()" /></countNo>
回答by m_pGladiator
回答by Luke Bennett
Try:
尝试:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit- had a brain freeze there, position() is more straightforward!
编辑- 在那里大脑冻结, position() 更直接!
回答by Arun Arangil
You can also run conditional statements on the Postion() which can be really helpful in many scenarios.
您还可以在 Postion() 上运行条件语句,这在许多情况下都非常有用。
for eg.
例如。
<xsl:if test="(position( )) = 1">
//Show header only once
</xsl:if>
回答by Santiago Cepas
<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>

