如何在XSL中将字符串中的逗号替换为撇号?
解决XSLT中CSV输出的逗号替换问题
你的代码存在两个关键问题:
- 语法错误:
replace函数的参数格式不正确,正确的参数顺序是replace(源字符串, 匹配正则, 替换值),你错误地拆分了参数括号。 - 匹配规则偏差:
[^a-zA-Z0-9]会替换所有非字母数字字符,但你只需要替换逗号。
针对XSLT 2.0及以上版本(主流处理器支持)
直接使用replace函数精准匹配逗号,注意XSLT中需用双单引号转义单个撇号:
<xsl:value-of select="replace(wd:HomeAddress/@wd:Descriptor, ',', '''')"/>
针对XSLT 1.0版本(兼容老环境)
XSLT 1.0无内置replace函数,需通过递归模板实现:
<!-- 定义替换逗号的递归模板 --> <xsl:template name="replace-comma-with-apostrophe"> <xsl:param name="input-text"/> <xsl:choose> <xsl:when test="contains($input-text, ',')"> <!-- 输出逗号前的内容 + 撇号 --> <xsl:value-of select="substring-before($input-text, ',')"/> <xsl:text>'</xsl:text> <!-- 递归处理剩余文本 --> <xsl:call-template name="replace-comma-with-apostrophe"> <xsl:with-param name="input-text" select="substring-after($input-text, ',')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <!-- 无逗号时直接输出原文本 --> <xsl:value-of select="$input-text"/> </xsl:otherwise> </xsl:choose> </xsl:template>
调用模板的写法:
<xsl:call-template name="replace-comma-with-apostrophe"> <xsl:with-param name="input-text" select="wd:HomeAddress/@wd:Descriptor"/> </xsl:call-template>
内容的提问来源于stack exchange,提问作者Philip G.
相关产品推荐
相关产品推荐

