Miguel J. Jiménez said:
Hi, I have the following node:
<node>
Some text[br] here with[br] lots of [br] inside it...
</node>
and I would like it to transfrom it using XSLT to the following:
Some text<br/> here with</br> lots of</br> inside it...
Being <br/> HTML tags and not simple text like <br/>
My trusty recursive search-and-replace will do this, but you
have to make judicious use of the disable-output-escaping
attribute:
- - -
<xsl:stylesheet version="1.0" xmlns:xsl="
http://www.w3.org/1999/XSL/Transform">
<xsl
utput method="xml" omit-xml-declaration="yes"/>
<!-- The main template -->
<xsl:template match="/">
<xsl:call-template name="replace">
<xsl:with-param name="text" select="node/text()"/>
<xsl:with-param name="from" select="'[br]'"/>
<xsl:with-param name="with" select="'<br/>'"/>
</xsl:call-template>
</xsl:template>
<!-- This is a recursive named template for search and replace. -->
<xsl:template name="replace">
<xsl
aram name="text"/>
<xsl
aram name="from"/>
<xsl
aram name="with"/>
<xsl:choose>
<xsl:when test="$from and contains($text,$from)">
<xsl:value-of select="substring-before($text,$from)"/>
<xsl:value-of disable-output-escaping="yes" select="$with"/>
<xsl:call-template name="replace">
<xsl:with-param name="text" select="substring-after($text,$from)"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="with" select="$with"/>
</xsl:call-template>
</xsl:when>
<xsl
therwise>
<xsl:value-of select="$text"/>
</xsl
therwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
- - -
A less general purpose template, but one that does not use
disable-output escaping for generating the new element
(which some might consider a nasty thing to do) is as
follows:
- - -
<xsl:stylesheet version="1.0" xmlns:xsl="
http://www.w3.org/1999/XSL/Transform">
<xsl
utput method="xml" omit-xml-declaration="yes"/>
<!-- The main template -->
<xsl:template match="/">
<xsl:call-template name="replace-element">
<xsl:with-param name="text" select="node/text()"/>
<xsl:with-param name="element" select="'br'"/>
</xsl:call-template>
</xsl:template>
<!-- Replace [element] with <element/> -->
<xsl:template name="replace-element">
<xsl
aram name="text"/>
<xsl
aram name="element"/>
<xsl:variable name="from" select="concat('[',$element,']')"/>
<xsl:choose>
<xsl:when test="contains($text,$from)">
<xsl:value-of select="substring-before($text,$from)"/>
<!-- here we create the new element -->
<xsl:element name="{$element}"/>
<xsl:call-template name="replace-element">
<xsl:with-param name="text" select="substring-after($text,$from)"/>
<xsl:with-param name="element" select="$element"/>
</xsl:call-template>
</xsl:when>
<xsl
therwise>
<xsl:value-of select="$text"/>
</xsl
therwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>