Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xslt 1.0 string replace function

Tags:

I have a string "aa::bb::aa"

and need to turn it in to "aa, bb, aa"

I have tried

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

but this returns "aa,,bb,,aa"

How can this be done.

like image 863
Paul Avatar asked Sep 22 '11 20:09

Paul


People also ask

What is current group () in XSLT?

Returns the contents of the current group selected by xsl:for-each-group. Available in XSLT 2.0 and later versions. Available in all Saxon editions. current-group() ➔ item()*

How do I replace text in XSLT?

With the help of the XSLT2. 0 replace () function removes undesired characters from a string in powerful regular expressions. XSLT replaces corresponding single characters, not the entire string. The dollar sign ($) interprets the rightmost characters in the string as literal.

What is Number () in XSLT?

Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit)

Can we reassign a value to variable in XSLT?

You cannot - 'variables' in XSLT are actually more like constants in other languages, they cannot change value. Save this answer.


1 Answers

A very simple solution (that will work as long as your string value doesn't have spaces):

translate(normalize-space(translate('aa::bb::cc',':',' ')),' ',',') 
  1. translate ":' into " "
  2. normalize-space() to collapse multiple whitespace characters into a single space " "
  3. translate single spaces " " into ","

A more robust solution would be to use a 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> 

You can use it like this:

<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> 
like image 101
Mads Hansen Avatar answered Sep 16 '22 22:09

Mads Hansen