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 & Sonas the value of the company field in a row of the database, we need to change it toJones ^& Sonbefore 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access