Monday, October 18, 2010

Removing line breaks in XSLT

I needed to remove the line breaks from my transform output because they were interfering with a 3rd party transform engine. (I could not use normalize-space(.) because I needed to preserve the spacing around mixed content.)

Instead of finding what the carriage return code is (I believe its #xD). I just created the variable $linebreak with the value of an actual linebreak.

The original code:
    <xsl:template match="para/text()">
<xsl:value-of select="."/>
</xsl:template>


Updated to remove line breaks:

<xsl:template match="para/text()">
<xsl:call-template name="selectWithoutBreaks"/>
</xsl:template>


Utilizes these templates:

<xsl:template name="selectWithoutBreaks" >

<!-- NOTE: The whitespace between the xsl:text elements is important because it represents the line break -->
<xsl:variable name="linebreak">
<xsl:text>
</xsl:text>
</xsl:variable>

<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="."/>
<xsl:with-param name="replace" select="$linebreak" />
<xsl:with-param name="with" select="''"/>
</xsl:call-template>
</xsl: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>


This is all possible in XSLT 1.0. If you are using XSLT 2.0 you can use the replace function instead of creating the replace-string template above.

No comments: