How to replace br tags with tags in XSL template?
Question
Let's assume I have a simple XML file:
<data>
<text>Hello world!<br>Nice to see you all!<br>Goodbye!</text>
</data>
Now I want to replace all <br>
strings with
strings so the result should be e.g.:
<transformed>
<text>Hello world! Nice to see you all! Goodbye!</text>
</transformed>
How do I do this?
XSL replace functionality is easy to implement (e.g. in http://geekswithblogs.net/Erik/archive/2008/04/01/120915.aspx) but the tricky part is to get the XSL transformer to output those
strings.. I either get invisible normal linefeed or &#10;
Perfect answer would be an XSL template which does the trick.
Solution
Use:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/data">
<transformed>
<text>
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="text" />
<xsl:with-param name="replace"><br></xsl:with-param>
<xsl:with-param name="by">&#10;</xsl:with-param>
</xsl:call-template>
</text>
</transformed>
</xsl:template>
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text, $replace)" />
<xsl:value-of select="$by" disable-output-escaping="yes" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
output:
<transformed>
<text>Hello world! Nice to see you all! Goodbye!</text>
</transformed>
NB!:
Set disable-output-escaping
attribute to yes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow