Chapter 1. Strings

I believe everybody in the world should have guns. Citizens should have bazookas and rocket launchers too. I believe that all citizens should have their weapons of choice. However, I also believe that only I should have the ammunition. Because frankly, I wouldn’t trust the rest of the goobers with anything more dangerous than [a] string.

Scott Adams

When it comes to manipulating strings, XSLT certainly lacks the heavy artillery of Perl. XSLT is a language optimized for processing XML markup, not strings. However, since XML is simply a structured form of text, string processing is inevitable in all but the most trivial transformation problems. Unfortunately, XSLT has only nine standard functions for string processing. Java, on the other hand, has about two dozen, and Perl, the undisputed king of modern text-processing languages, has a couple dozen plus a highly advanced regular-expression engine.

XSLT programmers have two choices when they need to perform advanced string processing. First, they can call out to external functions written in Java or some other language supported by their XSLT processor. This choice is wise if portability is not an issue and fairly heavy-duty string manipulation is needed. Second, they can implement the advanced string-handling functionality directly in XSLT. This chapter shows that quite a bit of common string manipulation can be done within the confines of XSLT. Advanced string capabilities are implemented in XSLT by combining the capabilities of the native string functions and by exploiting the power of recursion, which is an integral part of all advanced uses of XSLT. In fact, recursion is such an important technique in XSLT that it is worthwhile to look through some of these recipes even if you have no intention of implementing your string-processing needs directly in XSLT.

This book also refers to the excellent work of EXSLT.org, a community initiative that helps standardize extensions to the XSLT language. You may want to check out their site at http://www.exslt.org.

Testing if a String Ends with Another String

Problem

You need to test if a string ends with a particular substring.

Solution

substring($value, (string-length($value) - string-length($substr)) + 1) = $substr

Discussion

XSLT contains a native starts-with( ) function but no ends-with( ). However, as the previous code shows, ends-with can be implemented easily in terms of substring( ) and string-length( ). The code simply extracts the last string-length($substr) characters from the target string and compares them to the substring.

Warning

Programmers used to having the first position in a string start at index 0 should note that XSLT strings start at index 1.

Get XSLT Cookbook 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.