Using Recursion to Do Most Anything
Writing an XSLT stylesheet is different from programming in other languages. If you didn’t believe that before, you probably do now. We’ll finish this chapter with a couple of examples that demonstrate how to use recursion to solve the kinds of problems that you’re probably used to solving with procedural programming languages.
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 ...
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