2011-09-22 166 views
19

我有一個字符串 「AA :: BB :: AA」XSLT 1.0字符串替換功能

,需要把它在爲 「AA,BB,AA」

我已經試過

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

但是這返回「aa ,, bb,aa」

這怎麼能做到。

回答

66

一個非常簡單的解決方案(將工作,只要你的字符串值沒有空格):

translate(normalize-space(translate('aa::bb::cc',':',' ')),' ',',') 
  1. 翻譯「:」進 「」
  2. normalize-space()塌陷多將空白字符合併爲一個空格「」
  3. 將單個空格「」轉換爲「,」

一個更強大的解決方案是使用recursive template

<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> 
-1

您可以使用此

語法: - fn:tokenize(string,pattern)

Exa mple:tokenize("XPath is fun", "\s+")
結果:(「XPath」,「is」,「fun」)

+2

此問題標記爲XSLT 1.0。您的答案需要XSLT 2.0。 –