Using XPath function fn:replace from XSLT

28,393

Solution 1

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.

Solution 2

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 was able to make the replace work.

Share:
28,393
larsmoa
Author by

larsmoa

Working on Reveal, a high performance CAD viewer based on WebGL.

Updated on November 04, 2020

Comments

  • larsmoa
    larsmoa over 3 years

    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">
      <xsl:template match="/root">
        <html>
          <body>
            <!-- Replace \n with <p> -->
            <xsl:value-of select="fn:replace(value, '\n', '<p>')" />
          </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>
    

    The conversion fails on fn:replace with an NoSuchMethodException. If I change the replace statement to

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

    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.