XPath String Functions

XPath also includes a number of string functions.

String Functions

Here's a list of string functions you might find useful for your XPath expressions:

FunctionsDescription
starts-with(string1, string2)Returns true if the first string starts with the second string.
contains(string1, string2)Returns true if the first string contains the second string.
substring(stringoffsetlength)Returns a section of the string. The section starts at offset (which is a number), and is as long as the value provided at length (also a number).
substring-before(string1, string2)Returns the part of string1 up until the first occurence of string2.
substring-after(string1, string2)Returns the part of string1 after the first occurence of string2.
string-length(string)Returns the length of string (i.e. the number of characters).
normalize-space(string)Trims the leading and trailing space from string. Also replaces consecutive occurrences of white space with a single space.
translate(string1, string2, string3)Returns string1 after any matching characters in string2 have been replaced by the characters in string3.
concat(string1, string2, ...)Concatenates all strings (i.e. joins them together).
format-number(number1, string1, string2)Returns a formatted string version of number1 after applying string1 as a format string. string2 is an optional locale string.

Usage Example

The Source XML File

We'll use the following XML file, which contains a list of vegetables:

Copy to Clipboard
<?xml version="1.0"?>
<food_list>
  <food_item type="vegetable">
    <name>Agar</name>
  </food_item>
  <food_item type="vegetable">
    <name>Asparagus</name>
  </food_item>
  <food_item type="vegetable">
    <name>Cabbage</name>
  </food_item>
  <food_item type="vegetable">
    <name>Potato</name>
  </food_item>
  <food_item type="vegetable">
    <name>Pumpkin</name>
  </food_item>
  <food_item type="vegetable">
    <name>Yam</name>
  </food_item>
  <food_item type="vegetable">
    <name>Zucchini</name>
  </food_item>
</food_list>

The Requirement

Let's display the vegetable names in one column, and the string length of the vegetable name in another. Like this:

XPath string function example

The Solution

We could use the string-length() function in our XSL file to return the length of the string:

Copy to Clipboard
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="food_list">
  <table border="1" style="background-color:#cccc00">
    <tr>
      <th>Food Item</th>
      <th>String Length</th>
    </tr>
    <xsl:for-each select="food_item[position() <= 5]">  
    <tr>
      <td><xsl:value-of select="name"/></td>
      <td><xsl:value-of select="string-length(name)"/></td>
      </tr>
    </xsl:for-each>
  </table>
</xsl:template>

</xsl:stylesheet>

Enjoy this page?