XML
Beginner
1 min read
XPath Functions and Expressions
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)}')