Using Built-in XPath Functions on XML Data

XPath provides a powerful set of built-in functions designed to evaluate, manipulate, and extract data from XML documents. This article explores how to utilize four essential XPath functions—count(), concat(), substring(), and normalize-space()—to handle numeric calculations, string transformations, and text cleanup directly within your XML queries.

Sample XML Document

To demonstrate these functions, consider the following catalog.xml snippet:

<catalog>
    <book id="bk101">
        <title>  XML Developer's   Guide  </title>
        <author>Gambardella, Matthew</author>
        <price>44.95</price>
        <publish_date>2000-10-01</publish_date>
    </book>
    <book id="bk102">
        <title>Midnight Rain</title>
        <author>Ralls, Kim</author>
        <price>5.95</price>
        <publish_date>2000-12-16</publish_date>
    </book>
</catalog>

1. count(): Aggregating Nodes

The count() function returns an integer representing the total number of nodes matching a given node-set expression. It is commonly used for pagination, validation, and determining list sizes.


2. concat(): Combining Strings

The concat() function joins two or more strings together into a single string. It accepts at least two string arguments and concatenates them sequentially.


3. substring(): Extracting Portions of Text

The substring() function extracts a subset of characters from a source string, based on a 1-based start index and an optional length parameter.


4. normalize-space(): Cleaning Whitespace

The normalize-space() function removes leading and trailing whitespace from a string and replaces all internal sequences of whitespace characters (spaces, tabs, newlines) with a single space. If no argument is passed, it operates on the context node.


Combining Functions for Complex Queries

XPath functions can be nested to perform advanced operations in a single expression. For example, to create a clean, standardized bibliographic entry containing normalized text and extracted dates:

concat(
    normalize-space(/catalog/book[1]/author),
    " published '",
    normalize-space(/catalog/book[1]/title),
    "' in ",
    substring(/catalog/book[1]/publish_date, 1, 4)
)

Result: "Gambardella, Matthew published 'XML Developer's Guide' in 2000"