The translate() function can replace only one character with another single character (or an empty character (delete)). Thus, he cannot solve the problem of replacing strings.
Here is the complete XSLT 1.0 solution for the multi-replace problem :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my"> <xsl:output omit-xml-declaration="yes"/> <xsl:strip-space elements="*"/> <my:params xml:space="preserve"> <pattern> <old>
</old> <new><br/></new> </pattern> <pattern> <old>quick</old> <new>slow</new> </pattern> <pattern> <old>fox</old> <new>elephant</new> </pattern> <pattern> <old>brown</old> <new>white</new> </pattern> </my:params> <xsl:variable name="vPats" select="document('')/*/my:params/*"/> <xsl:template match="text()" name="multiReplace"> <xsl:param name="pText" select="."/> <xsl:param name="pPatterns" select="$vPats"/> <xsl:if test="string-length($pText) >0"> <xsl:variable name="vPat" select= "$vPats[starts-with($pText, old)][1]"/> <xsl:choose> <xsl:when test="not($vPat)"> <xsl:copy-of select="substring($pText,1,1)"/> </xsl:when> <xsl:otherwise> <xsl:copy-of select="$vPat/new/node()"/> </xsl:otherwise> </xsl:choose> <xsl:call-template name="multiReplace"> <xsl:with-param name="pText" select= "substring($pText, 1 + not($vPat) + string-length($vPat/old/node()))"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet>
when this conversion is applied to the following XML document:
<t>The quick brown fox</t>
required, the correct result is obtained :
The slow<br />white elephant
Explanation
A named template is used that calls itself recursively.
All pairs with several substitutions -> replaced pairs are provided in one external parameter, which for convenience is indicated here as a built-in element of the global level <my:params> .
The recursion takes every single character in the source string (from left to right) and finds the first pattern that starts with that character at that position in the string.
Replacement can be not only a string, but also any node. In this particular case, we replace each NL character with <br/> .
source share