我在分配计数器变量并递增它然后在XSLT中检查某个值时遇到了一些困难.这是我的代码:
- <?xml version="1.0" encoding="utf-8"?>
- <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:variable name="empty_string"/>
- <xsl:variable name="counter" select="0"/>
- <xsl:template match="/Collection">
- <xsl:for-each select="Content">
- <xsl:sort select="Html/root/Event/start_date" order="ascending"/>
- <xsl:variable name="isFutureEvent">
- <xsl:value-of select="syscom:isFutureDate(Html/root/Event/start_date)" />
- </xsl:variable>
- <xsl:if test="Html/root/Event != $empty_string">
- <xsl:if test="$isFutureEvent='true'">
- <!-- Increment Counter -->
- <xsl:value-of select="$counter + 1"/>
- <!-- Test if Counter < 4 -->
- <xsl:if test="$counter < 3">
- <div class="media">
- <!-- Do stuff here -->
- </div>
- </xsl:if> <!-- End if for counter -->
- </xsl:if>
- </xsl:if>
- <!--</xsl:when>-->
- <!--</xsl:choose>-->
- </xsl:for-each>
- </xsl:template>
- </xsl:stylesheet>
XSL中的“变量”实际上是常量 – 你无法改变它们的价值.这个:
- <xsl:value-of select="$counter + 1"/>
只会输出$counter 1的值
要做循环,你必须使用递归 – 例如:
- <xsl:stylesheet
- version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
- <xsl:template name="loop">
- <xsl:param name="i"/>
- <xsl:param name="limit"/>
- <xsl:if test="$i <= $limit">
- <div>
- <xsl:value-of select="$i"/>
- </div>
- <xsl:call-template name="loop">
- <xsl:with-param name="i" select="$i+1"/>
- <xsl:with-param name="limit" select="$limit"/>
- </xsl:call-template>
- </xsl:if>
- </xsl:template>
- <xsl:template match="/">
- <html>
- <body>
- <xsl:call-template name="loop">
- <xsl:with-param name="i" select="0"/>
- <xsl:with-param name="limit" select="10"/>
- </xsl:call-template>
- </body>
- </html>
- </xsl:template>
- </xsl:stylesheet>
尽管最好避免循环 – 在大多数情况下,可以编写XSL来避免循环,但是我不太了解你想要实现什么来为你提供完整的解决方案.