SyntaxStudy
Sign Up
XML XPath Functions and Expressions
XML Beginner 1 min read

XPath Functions and Expressions

XPath 1.0 provides a library of built-in functions organized into four groups: node-set functions, string functions, numeric functions, and boolean functions. Node-set functions include count(), sum(), last(), position(), id(), local-name(), namespace-uri(), and name(). String functions include string(), concat(), contains(), starts-with(), substring(), substring-before(), substring-after(), string-length(), normalize-space(), and translate(). Numeric functions include number(), floor(), ceiling(), and round(). Boolean functions include boolean(), not(), true(), false(), and lang(). XPath expressions operate on four data types: node-set (an unordered collection of nodes), string, number, and boolean. Automatic type conversion occurs in many contexts — for example, a node-set is converted to a string by taking the string-value of its first node when used in a string context. Numbers follow IEEE 754 floating-point rules, and the special values NaN (not a number) and Infinity can arise from operations like dividing by zero. In Python, the lxml library provides full XPath 1.0 support through the element.xpath() method and the etree.XPath() compiled expression class. Namespace prefixes used in the XPath string must be registered in a dictionary passed to the namespaces parameter. In Java, the javax.xml.xpath package provides the XPath, XPathExpression, and XPathConstants classes for evaluating XPath expressions against DOM documents or SAX input sources.
Example
# Python: XPath with lxml

from lxml import etree

xml_data = b"""<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book id="b001" category="fiction">
        <title>The Great Gatsby</title>
        <author>F. Scott Fitzgerald</author>
        <year>1925</year>
        <price>12.99</price>
    </book>
    <book id="b002" category="non-fiction">
        <title>Clean Code</title>
        <author>Robert C. Martin</author>
        <year>2008</year>
        <price>35.00</price>
    </book>
</library>"""

root = etree.fromstring(xml_data)

# Basic selection
books = root.xpath('//book')
print(f'Books found: {len(books)}')

# Predicate filter
fiction = root.xpath("//book[@category='fiction']")
print(f'Fiction: {fiction[0].find("title").text}')

# Numeric functions
total = root.xpath('sum(//price)')
print(f'Total price: {total}')          # 47.99

count = root.xpath('count(//book)')
print(f'Count: {int(count)}')           # 2

# String functions
titles = root.xpath("//title[contains(text(), 'Code')]/text()")
print(f'Contains "Code": {titles}')

# last() and position()
last_book = root.xpath('//book[last()]/title/text()')
print(f'Last book: {last_book}')

# Compiled expression (more efficient for repeated use)
get_ids = etree.XPath('//book/@id')
ids = get_ids(root)
print(f'IDs: {list(ids)}')