Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xslt replace \n with <br/> only in one node?

Tags:

xslt

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

string1
string 2
sting3

but however when it renders, it renders all one line how can i replace all \n with <br />'s.

i've tried

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

but i get this error

Error loading stylesheet: Invalid XSLT/XPath function.

how do i do this?

like image 965
Matthew Deloughry Avatar asked Feb 18 '09 14:02

Matthew Deloughry


People also ask

How do I remove special characters from a string in XSLT?

The inner translate( ) removes all characters of interest (e.g., numbers) to obtain a from string for the outer translate( ) , which removes these non-numeric characters from the original string.

How do you replace in XSLT?

XSLT replace is deterministic and does string manipulation that replaces a sequence of characters defined inside a string that matches an expression. In simple terms, it does string substitution in the specified place by replacing any substrings. Fn: replace function is not available in XSLT1.

How do you use conditional in XSLT?

To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document.


1 Answers

Call this template on the string you want to process:

<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>

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

like image 119
Tomalak Avatar answered Oct 05 '22 03:10

Tomalak