[2.0] Using the XPath 2.0 replace() Function to Avoid Recursion

Because string manipulation is a common task in transforming documents, XPath 2.0 provides the very useful replace() function. This lets us provide the original string, the string we want to replace, and the string we want substituted in its place. To review our earlier example, we want to make three replacements in our text:

  • Any ampersand (&) should have a caret added in front of it (^&).

  • Any vertical bar (|) should have a caret added in front of it (^|).

  • Any single quote (') should be replaced with two single quotes ('').

Our stylesheet to perform these tasks looks like this:

<?xml version="1.0"?>
<!-- string_replace-2_0.xsl -->
<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:apply-templates select="ul/li"/>
  </xsl:template>

  <xsl:template match="li">
    <xsl:variable name="sub1" select="replace(., '&amp;', '^&amp;')"/>
    <xsl:variable name="sub2" select="replace($sub1, '\|', '^|')"/>
    <xsl:value-of select='replace($sub2, "&apos;", "&apos;&apos;")'/>
    <xsl:text>&#xA;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

We get the same results we got from our much longer XSLT 1.0 stylesheet:

This is a test ^& I hope it works ^| fails gracefully
Some techniques are simpler ^& easier than recursion
Will I enjoy next Tuesday''s meeting?

This example is far simpler than the recursive technique we used in the XSLT 1.0 stylesheet. Both of them generate the ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.