XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round three / String processing

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 3.)

Node string values have already appeared in output, xsl:if tests and elsewhere. Often the processor handles strings without extra thought.

Often you need string length, substring containment or starting-text tests, character removal or substring extraction before further processing.

String functions do all this and more. With variables and named templates, they support recursive information processing. XPath 2.0 offers many such functions, including regular-expression functions. Functions fn:contains(), fn:ends-with() and fn:starts-with() and regular-expression function fn:matches() appeared in the preceding section.

XPath also converts arbitrary input to strings with fn:string(). This is not really a string function: it produces strings rather than operating on them.

Other XPath string functions include:

String functions in XPath 2.0:
fn:compare(), fn:concat(), fn:escape-uri(), fn:lower-case(), fn:normalize-space(), fn:normalize-unicode(), fn:string-length(), fn:string-join(), fn:substring(), fn:substring-after(), fn:substring-before(), fn:translate(), fn:upper-case()

Plus two further regular-expression functions:
fn:replace(), fn:tokenize()

Chapter 5 discusses them in detail in XSLT and XPath function reference. Here only a few are illustrated.

Function fn:string-length() counts characters in its argument. Without an argument, it returns the current context item’s string length.

Characters represented in source by character entities, such as E, or XML entity references, such as &, count as a single character in expanded form. The XSLT processor cannot access the original source: the document has already passed through the XML parser and each reference has become one character. Parsed text entities similarly count as the characters in their expansion.

Function fn:substring() extracts a substring with defined start and optional length. The starting index should sensibly be a positive integer. The indexed character is included in the result.

Function fn:substring-after() returns the portion after the first occurrence of a test string, which may have one or many characters. If absent, or if input is empty, the result is empty.

Function fn:substring-before() returns the portion before the first test-string occurrence, again allowing one or many characters.

If the test is absent or either string is empty, the result is empty.

Function fn:translate() replaces individual characters: a character found in the comparison list is replaced with the corresponding-position character in the replacement list.

Recursive templates versus regular expressions

XSLT 1.0 needed complex recursive templates for many routine tasks. XSLT 2.0 still permits them but often offers alternatives. Compare word counting: the first approach uses a named template calling itself through the text. The second uses an XPath 2.0 regular-expression function to do the same elegantly.

The XSLT 1.0 and XPath 1.0 recursive approach

First, a word counter compatible with XSLT 1.0. The prefix fn is therefore omitted from function names.

<!-- Zahl der Worte im Stringvalue des current node: -->
<xsl:template name="wortezaehlen">
  <!-- Parameter nimmt Text von außen entgegen: -->
  <xsl:param name="text" select=""/>
  <!-- Zählparameter speichert Zählerstand: -->
  <xsl:param name="zahl" select="1"/>
  <!-- die Eingabe normalisieren: -->
  <xsl:variable name="text_n" select="concat(normalize-space($text),' ')"/>
  <!-- erstes Wort abtrennen, mit dem Rest weiterarbeiten: -->
  <xsl:variable name="rest" select="substring-after($text_n,' ')"/>
  <xsl:choose>
    <!-- wenn es einen Rest gibt: -->
    <xsl:when test="$rest">
      <!-- den Zähler um eins hochzählen: -->
      <xsl:variable name="zaehler" select="$zahl + 1"/>
      <!-- und das Template neu aufrufen: -->
      <xsl:call-template name="wortezaehlen">
         <xsl:with-param name="text" select="$rest"/>
         <xsl:with-param name="zahl" select="$zaehler"/>
      </xsl:call-template>
    </xsl:when>
    <!-- wenn nichts übrig ist: -->
    <xsl:otherwise>
      <!-- letzten Zählerstand ausgeben: -->
      <xsl:value-of select="$zahl"/>
      <!-- ... quasi der Rückgabewert des Templates! -->
    </xsl:otherwise>
  </xsl:choose>
<!-- Ende des Zähltemplates -->
</xsl:template>

Code example: kap03/3.04/wortezaehlen.xsl (excerpt).

Initially pass the context node’s string value and initialize a counter. Inside, complex processing uses substring-after() to remove words one by one. Recursion passes the remainder and incremented counter until no remainder remains, then outputs the final count.

This remains a useful study of intermediate variables, parameter passing and conditional recursive call. It still runs in XSLT 2.0, but the more modern alternative uses new function fn:tokenize().

The XSLT 2.0 and XPath 2.0 approach

The source-length difference is revealing:

 <!-- Worte im Stringvalue des current node -->
 <xsl:template name="wortezaehlen">
   <xsl:param name="text" select=""/>
   <xsl:value-of select="fn:count(fn:tokenize(fn:normalize-space($text), ' '))"/>
 <!-- Ende des Zähltemplates -->
 </xsl:template>
  

Code example: kap03/3.04/wortezaehlen2.xsl (excerpt).

The principle is similar but the implementation entirely different. A named template still receives the current node’s string value, but no recursion occurs. All work moves into a regular-expression string function receiving normalized text.

Function tokenize() splits at word boundaries using its second argument, here a space. The resulting sequence of words is counted by count() and output directly.

A separate template is now optional, unlike the recursive version.

Execution times make the comparison more interesting. Saxon reports timing with option -t. The regular-expression template takes 16 ms versus 32 ms for recursion. Modernizing old stylesheets with XPath 2.0 is therefore worthwhile even if the old approach still works.

   

back to top