Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

variables - Increment a value in XSLT

I'm reasonably new to xlst and am confused as to whether there is any way to store a value and change it later, for example incrementing a variable in a loop.

I'm a bit baffled by not being able to change the value of a after it's set doesn't make sense to me, making it more of a constant.

For example I want to do something like this:

<xsl:variable name="i" select="0" />
<xsl:for-each select="data/posts/entry">
    <xsl:variable name="i" select="$i + 1" />
    <!-- DO SOMETHING -->
</xsl:for-each>

If anyone can enlighten me on whether there is an alternative way to do this
Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

XSLT is a functional language and among other things this means that variables in XSLT are immutable and once they have been defined their value cannot be changed.

Here is how the same effect can be achieved in XSLT:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
   <posts>
    <xsl:for-each select="data/posts/entry">
        <xsl:variable name="i" select="position()" />
        <xsl:copy>
         <xsl:value-of select="concat('$i = ', $i)"/>
        </xsl:copy>
    </xsl:for-each>
   </posts>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<data>
 <posts>
  <entry/>
  <entry/>
  <entry/>
  <entry/>
  <entry/>
 </posts>
</data>

the result is:

<posts>
    <entry>$i = 1</entry>
    <entry>$i = 2</entry>
    <entry>$i = 3</entry>
    <entry>$i = 4</entry>
    <entry>$i = 5</entry>
</posts>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...