XSLT 1.0字符串替换函数

27

我有一个字符串 "aa::bb::aa",

需要将其转换为 "aa, bb, aa"。

我已经尝试过

translate(string,':',', ')

但是这将返回"aa,,bb,,aa"。

如何解决这个问题。

2个回答

77

一种非常简单的解决方案(只要您的字符串值没有空格即可):

translate(normalize-space(translate('aa::bb::cc',':',' ')),' ',',')
  1. 将 ":' 翻译成 " "
  2. normalize-space() 将多个空格字符折叠成一个空格符 " "
  3. 将单个空格符 " " 翻译成 ","

更健壮的解决方案是使用递归模板

<xsl:template name="replace-string">
    <xsl:param name="text"/>
    <xsl:param name="replace"/>
    <xsl:param name="with"/>
    <xsl:choose>
      <xsl:when test="contains($text,$replace)">
        <xsl:value-of select="substring-before($text,$replace)"/>
        <xsl:value-of select="$with"/>
        <xsl:call-template name="replace-string">
          <xsl:with-param name="text"
select="substring-after($text,$replace)"/>
          <xsl:with-param name="replace" select="$replace"/>
          <xsl:with-param name="with" select="$with"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

你可以这样使用:
<xsl:call-template name="replace-string">
  <xsl:with-param name="text" select="'aa::bb::cc'"/>
  <xsl:with-param name="replace" select="'::'" />
  <xsl:with-param name="with" select="','"/>
</xsl:call-template>

-3
你可以使用这个:
语法:- fn:tokenize(string,pattern) 示例:tokenize("XPath is fun", "\s+")
结果:("XPath", "is", "fun")

8
这个问题被标记为XSLT 1.0。您的答案需要使用XSLT 2.0。 - michael.hor257k

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接