xslt

Replace \n with <br/> in one node?


I have a node <msg> which contains a message such as

string1
string 2
sting3

however when it renders, it renders all on one line.

How can i replace all \n with <br /> elements?

I've tried

<xsl:value-of select='replace(msg, "&amp;#xA;", "&lt;br/&gt;")' />

but I get this error

Error loading stylesheet: Invalid XSLT/XPath function.

How do I do this?


Solution

  • You are working with an XSLT 1.0 processor, whereas replace() is a function that has been introduced with XSLT/XPath 2.0.

    Call this template on the string you want to process instead:

    <xsl:template name="break">
      <xsl:param name="text" select="string(.)"/>
      <xsl:choose>
        <xsl:when test="contains($text, '&#xa;')">
          <xsl:value-of select="substring-before($text, '&#xa;')"/>
          <br/>
          <xsl:call-template name="break">
            <xsl:with-param 
              name="text" 
              select="substring-after($text, '&#xa;')"
            />
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$text"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:template>
    

    Like this (it will work on the current node):

    <xsl:template match="msg">
      <xsl:call-template name="break" />
    </xsl:template>
    

    or like this, explicitly passing a parameter:

    <xsl:template match="someElement">
      <xsl:call-template name="break">
        <xsl:with-param name="text" select="msg" />
      </xsl:call-template>
    </xsl:template>