I have an element which contains a large text string in which I need to replace
all \ with \\ and all newlines with \n and all tabs with \t etc.
I use this template to do the replacement
<xsl:template name="replaceCharacter" >
<xsl:param name="StringToTransform"/>
<xsl:param name="characterToReplace"/>
<xsl:param name="characterToInsert"/>
<xsl:choose>
<xsl:when test="contains($StringToTransform,$characterToReplace)">
<xsl:value-of
select="normalize-space(substring-before($StringToTransform,$characterToReplace))"/>
<xsl:value-of select="$characterToInsert"/>
<xsl:call-template name="replaceCharacter">
<xsl:with-param name="StringToTransform"
select="substring-after($StringToTransform, $characterToReplace)"/>
<xsl:with-param name="characterToReplace" select="$characterToReplace"/>
<xsl:with-param name="characterToInsert" select="$characterToInsert"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="normalize-space($StringToTransform)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
If i call the template to escape the back slashes of my Key element first, then
the second call to the replace template that should escape newlines does not
find any newlines. When I remove the calls to normalize-space it works just
fine - however my input XML element must be "trimmed" of excess spaces in the
start and end of the string - so I have to normalize spaces, don't I?
I thought that normalize-space would just remove the spaces in the beginning
and end of the string - not all newlines inside the string - or am I missing
something here?
Here are the two calls that replaces back slashes and newlines:
<!-- Escapes all back slashes (ASCII code 92) -->
<xsl:variable name="keyEscapedBackSlash">
<xsl:call-template name="replaceCharacter">
<xsl:with-param name="StringToTransform">
<xsl:copy-of select="."/>
</xsl:with-param>
<xsl:with-param name="characterToReplace" select="'\'"/>
<xsl:with-param name="characterToInsert" select="'\\'"/>
</xsl:call-template>
</xsl:variable>
<!-- Escapes all newlines (ASCII code 10) -->
<xsl:variable name="keyEscapedNewline">
<xsl:call-template name="replaceCharacter">
<xsl:with-param name="StringToTransform">
<xsl:copy-of select="$keyEscapedBackSlash"/>
</xsl:with-param>
<xsl:with-param name="characterToReplace" select="' '"/>
<xsl:with-param name="characterToInsert" select="'\n'"/>
</xsl:call-template>
</xsl:variable >
Any suggestions will be much appreciated.
Regards,
Flemming Joensson, Software Engineer.
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list