Implementing a String Replace Function

To demonstrate how to use recursion to solve problems, we’ll write a string replace function. This is sometimes useful when you need to escape certain characters or substrings in your output. The stylesheet we’ll develop here transforms an XML document into a set of SQL statements that will be executed at a Windows command prompt. We have to do several things:

Put a caret (^) in front of all ampersands (&)

On the Windows NT and Windows 2000 command prompt, the ampersand means that the current command has ended and another is beginning. For example, this command creates a new directory called xslt and changes the current directory to the newly created one:

mkdir xslt & chdir xslt

If we create a SQL statement that contains an ampersand, we’ll need to escape the ampersand so it’s processed as a literal character, not as an operator. If we insert the value Jones & Son as the value of the company field in a row of the database, we need to change it to Jones ^& Son before we try to run the SQL command.

Put a caret (^) in front of all vertical bars (|)

The vertical bar is the pipe operator on Windows systems, so we need to escape it if we want it interpreted as literal text instead of an operator.

Replace any single quote (') with two single quotes ('')

This is a requirement of our database system.

Procedural design

Three functions we could use in our template are concat(), substring-before(), and substring-after(). To replace an ampersand with a caret and ...

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.