tags:

views:

763

answers:

1

I'm trying to use XSLT to convert a simple XML schema to HTML and planned to use fn:replace to replace returns (\n) with <p>. However, I can't figure out how to use this function properly.

A simplified version of the XSLT I'm using reads:

<?xml version="1.0"?>

<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                xmlns:fn="http://www.w3.org/2005/xpath-functions"&gt;
  <xsl:template match="/root">
    <html>
      <body>
        <!-- Replace \n with <p> -->
        <xsl:value-of select="fn:replace(value, '\n', '&lt;p&gt;')" />
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

And the input to this XLST is e.g.:

<?xml version="1.0"?>

<root>
  <value><![CDATA[
    Hello
    world!
  ]]></value>
</root>

However, the conversion fails on fn:replace with an NoSuchMethodException. Note if I change the replace statement to

<xsl:value-of select="fn:replace('somestring', '\n', '&lt;p&gt;')" />

I get an IllegalArgumentException. How do I use fn:replace to achieve what I want?

I'm using Butterfly XML Editor to test the XSLT.

+2  A: 

XPath 2.0 has a replace function that you can use with any XSLT 2.0 processor like Saxon 9 or AltovaXML tools or Gestalt. You seem to try to use the function with an XSLT 1.0 processor, that is not going to work. In case you are restricted to an XSLT 1.0 processor you will need to implement the replacement with a named recursive template or with the help of an extension.

However note that even with XSLT 2.0 your attempt to use replace seems wrong as you will produce a text node with a 'p' tag markup while I assume you want to create a 'p' element node in the result. So even with XSLT 2.0 using analyze-string instead of replace is more likely to get you the result you want.

Martin Honnen
Thx, mentioning XSLT 2.0 pushed me in the right direction. By bumping the version attribute of <xsl:stylesheet>; to 2.0 and using <xsl:value-of select="replace(description, '\n', '<p/>')" disable-output-escaping="yes" />; I get the job done. Maybe analyze-string is cleaner but this gets the job done :)
larsm