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

如何用XSLT 2.0将字符串重复拼接n次并设为变量?

解决XSLT 2.0重复拼接字符串的问题

你的代码无法得到预期结果,核心原因是XSLT中的变量是不可变的——你在<xsl:for-each>内部定义的$path是局部变量,不会修改外部同名变量的值,最终外部的$path仍然是空字符串。

下面是两种可行的实现方式:

方法一:用string-join结合序列生成(推荐,简洁高效)

利用XSLT 2.0的序列生成能力,直接生成包含n个../的序列,再通过string-join拼接成字符串:

<xsl:variable name="count-dirs" select="count(tokenize($target-filepath, '/')) - 1"/>
<xsl:variable name="path" select="string-join(for $i in 1 to $count-dirs return '../', '')"/>
  • for $i in 1 to $count-dirs return '../':生成一个包含$count-dirs个../的字符串序列
  • string-join(..., ''):将序列中的所有元素用空字符串连接,得到最终拼接结果

方法二:用<xsl:for-each>结合结果树片段(兼容传统写法)

如果偏好循环写法,可以通过收集循环内的输出内容来构建最终字符串:

<xsl:variable name="count-dirs" select="count(tokenize($target-filepath, '/')) - 1"/>
<xsl:variable name="path">
  <xsl:for-each select="1 to $count-dirs">
    <xsl:text>../</xsl:text>
  </xsl:for-each>
</xsl:variable>

这里的$path会被自动转换为字符串类型,包含循环输出的所有../内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:25:20