You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于xsl:number实现XSL变量计数器降序输出的问题

XSLT 降序年份计数实现方案

问题背景

  • 需要通过变量实现日期的降序计数,本次简化为仅对年份进行处理,示例预期输出为2017、2016的降序排列
  • 使用变量是为了适配完整代码中调用JSON数据的需求
  • 现有公开的降序计数相关方案均未结合变量实现,无法直接复用

问题说明

现有代码输出为升序排列,不符合预期。

现有XSLT代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output method="html" indent="yes" html-version="5"/>
<xsl:template match="data">
<xsl:for-each select="1 to 2">
<xsl:variable name="counter">
<xsl:number start-at="2016" value="position()"/>
</xsl:variable>
<xsl:value-of select="$counter"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

当前输出

<!DOCTYPE HTML>20162017

预期输出

<!DOCTYPE HTML>20172016

解决方案

方案1:最小改动适配(倒序遍历序列)

仅需修改xsl:for-each的遍历序列为逆序即可,其余逻辑保持不变:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output method="html" indent="yes" html-version="5"/>
<xsl:template match="data">
<!-- 改动点:使用reverse()翻转遍历序列 -->
<xsl:for-each select="reverse(1 to 2)">
<xsl:variable name="counter">
<xsl:number start-at="2016" value="position()"/>
</xsl:variable>
<xsl:value-of select="$counter"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

实现原理:reverse()函数会将1 to 2的序列转为[2,1],第一次循环position()值为2,结合start-at="2016"计算得到2017,第二次循环position()值为1,得到2016,符合降序要求。

方案2:变量适配方案(更适合对接JSON数据源)

如果后续需要从JSON中读取起始、结束年份,建议直接通过变量计算年份值,扩展性更强:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output method="html" indent="yes" html-version="5"/>
<xsl:template match="data">
<!-- 后续可将起始、结束年份替换为JSON数据源读取的变量 -->
<xsl:variable name="start-year" select="2016"/>
<xsl:variable name="end-year" select="2017"/>
<xsl:for-each select="1 to ($end-year - $start-year + 1)">
<xsl:variable name="counter" select="$end-year - position() + 1"/>
<xsl:value-of select="$counter"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

实现原理:通过结束年份减去当前循环位置再加1,直接得到降序的年份值,变量可自由绑定外部数据源的取值,适配性更高。


内容的提问来源于stack exchange,提问作者Toolbox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:12:03