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

XSLT 1.0多字符替换问题:如何将逗号替换为XX

解决XSLT中逗号替换为XX的问题

你用translate函数不行是因为它是单字符映射替换:第二个参数里的每个字符只会对应替换第一个参数里的对应位置字符,多余的字符会被忽略。你写的translate(item, ',', 'XX')其实是把逗号替换成第二个参数的第一个字符X,第二个X根本没起作用。

下面分版本给解决方案:

方案一:XSLT 2.0及以上版本(推荐)

直接用replace()函数,它支持多字符替换,语法更直观:

完整XSLT示例:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <item>
      <xsl:value-of select="replace(item, ',', 'XX')"/>
    </item>
  </xsl:template>
</xsl:stylesheet>

这个会把所有逗号替换成XX,正好得到你要的结果。

方案二:XSLT 1.0版本(兼容旧环境)

XSLT 1.0没有replace,得用递归模板处理:

完整XSLT示例:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- 匹配根节点,输出item元素 -->
  <xsl:template match="/">
    <item>
      <xsl:call-template name="replace-comma">
        <xsl:with-param name="text" select="item"/>
      </xsl:call-template>
    </item>
  </xsl:template>

  <!-- 递归替换逗号的模板 -->
  <xsl:template name="replace-comma">
    <xsl:param name="text"/>
    <xsl:choose>
      <!-- 如果文本里还有逗号,拆分替换后递归 -->
      <xsl:when test="contains($text, ',')">
        <xsl:value-of select="substring-before($text, ',')"/>
        <xsl:text>XX</xsl:text>
        <xsl:call-template name="replace-comma">
          <xsl:with-param name="text" select="substring-after($text, ',')"/>
        </xsl:call-template>
      </xsl:when>
      <!-- 没有逗号了,直接输出剩余文本 -->
      <xsl:otherwise>
        <xsl:value-of select="$text"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

这个模板会逐个查找文本里的逗号,替换成XX后继续处理剩下的内容,直到所有逗号都被替换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:10:25