tags:

views:

169

answers:

2

how to convert NEWLINE into <BR/> with XSLT?

I have

<text>
some text with 
new lines
</text>

I want to have

<p> some text with <br /> new lines </p>
+3  A: 

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="t">
  <p>
    <xsl:apply-templates/>
  </p>
 </xsl:template>

 <xsl:template match="text()" name="insertBreaks">
   <xsl:param name="pText" select="."/>

   <xsl:choose>
     <xsl:when test="not(contains($pText, '&#xA;'))">
       <xsl:copy-of select="$pText"/>
     </xsl:when>
     <xsl:otherwise>
       <xsl:value-of select="substring-before($pText, '&#xA;')"/>
       <br />
       <xsl:call-template name="insertBreaks">
         <xsl:with-param name="pText" select=
           "substring-after($pText, '&#xA;')"/>
       </xsl:call-template>
     </xsl:otherwise>
   </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>Line1
Line2
Line3
</t>

produces the wanted, correct result:

<p>Line1<br />Line2<br />Line3<br /></p>
Dimitre Novatchev
It doesn't work. I use jquery.xslt.js to make translation. Do you think it does matter?
liysd
@liysd: I have corrected my answer. Try it now.
Dimitre Novatchev
@liysd: Now, it works. @Dimitre: +1 also because I like this recursion pattern.
Alejandro
@Alejandro: I knew you'd like it, otherwise I'd recommend using FXSL's `str-map()` :)
Dimitre Novatchev
@Dimitre: Thanks! It started to work when I changed "text()" to "text" (I use tag <text> instead of <t> in your example).
liysd
it doesn't work with internet explorer. I jquery.xslt.js ends with error.
liysd
@liysd: Try never to write: "it doesn't work". Always explain what is "it" and what is "not working". So "it" was working before and now "it" is "not working"? Probably the change in behavior is only due that it started raining today?
Dimitre Novatchev