xml – 在XSLT中递增和检查计数器变量

前端之家收集整理的这篇文章主要介绍了xml – 在XSLT中递增和检查计数器变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在分配计数器变量并递增它然后在XSLT中检查某个值时遇到了一些困难.这是我的代码
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:variable name="empty_string"/>
  3. <xsl:variable name="counter" select="0"/>
  4. <xsl:template match="/Collection">
  5. <xsl:for-each select="Content">
  6. <xsl:sort select="Html/root/Event/start_date" order="ascending"/>
  7. <xsl:variable name="isFutureEvent">
  8. <xsl:value-of select="syscom:isFutureDate(Html/root/Event/start_date)" />
  9. </xsl:variable>
  10.  
  11. <xsl:if test="Html/root/Event != $empty_string">
  12. <xsl:if test="$isFutureEvent='true'">
  13. <!-- Increment Counter -->
  14. <xsl:value-of select="$counter + 1"/>
  15. <!-- Test if Counter < 4 -->
  16. <xsl:if test="$counter &lt; 3">
  17. <div class="media">
  18. <!-- Do stuff here -->
  19. </div>
  20. </xsl:if> <!-- End if for counter -->
  21. </xsl:if>
  22. </xsl:if>
  23. <!--</xsl:when>-->
  24. <!--</xsl:choose>-->
  25. </xsl:for-each>
  26. </xsl:template>
  27. </xsl:stylesheet>

但它似乎没有增加我的计数器,并且当计数器击中时没有退出3.对此有任何帮助吗?

XSL中的“变量”实际上是常量 – 你无法改变它们的价值.这个:
  1. <xsl:value-of select="$counter + 1"/>

只会输出$counter 1的值

要做循环,你必须使用递归 – 例如:

  1. <xsl:stylesheet
  2. version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.  
  4. <xsl:template name="loop">
  5. <xsl:param name="i"/>
  6. <xsl:param name="limit"/>
  7. <xsl:if test="$i &lt;= $limit">
  8. <div>
  9. <xsl:value-of select="$i"/>
  10. </div>
  11. <xsl:call-template name="loop">
  12. <xsl:with-param name="i" select="$i+1"/>
  13. <xsl:with-param name="limit" select="$limit"/>
  14. </xsl:call-template>
  15. </xsl:if>
  16. </xsl:template>
  17.  
  18. <xsl:template match="/">
  19. <html>
  20. <body>
  21. <xsl:call-template name="loop">
  22. <xsl:with-param name="i" select="0"/>
  23. <xsl:with-param name="limit" select="10"/>
  24. </xsl:call-template>
  25. </body>
  26. </html>
  27. </xsl:template>
  28.  
  29. </xsl:stylesheet>

尽管最好避免循环 – 在大多数情况下,可以编写XSL来避免循环,但是我不太了解你想要实现什么来为你提供完整的解决方案.

猜你在找的XML相关文章