xslt 1.0字符串替换函数

Pau*_*aul 21 xslt xslt-1.0

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

并需要把它变成"aa,bb,aa"

我试过了

translate(string,':',', ')
Run Code Online (Sandbox Code Playgroud)

但这会返回"aa ,, bb ,, aa"

如何才能做到这一点.

Mad*_*sen 70

一个非常简单的解决方案(只要你的字符串值没有空格就可以工作):

translate(normalize-space(translate('aa::bb::cc',':',' ')),' ',',')
Run Code Online (Sandbox Code Playgroud)
  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>
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

<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>
Run Code Online (Sandbox Code Playgroud)