XPath: Node Selection, Axes, Predicates, and Functions

Unit 5CLO03

Learning Objectives

Course Learning Outcomes

CLO03

Course Outcomes

CO04
ℹ️

Introduction

XPath is the query backbone for XML. XSLT, XQuery, DOM APIs, and validators all lean on it. You will learn to move across the tree with axes, filter with predicates, and compute with built-in functions.

Study tracker

Mark what you have completed for this topic.

0% done

The Basics

Essentials

  • Absolute path starts with /; relative starts at the current node.
  • Predicates [ ] filter nodes by position or condition.
  • Axes describe direction: child, parent, ancestor, descendant, following-sibling, preceding-sibling, attribute.
  • Functions help aggregate, test, and convert values.

Technical Details

Syntax patterns

Common selections

/library/book/title
//book[@id='b2']/price
//book[price > 500]
//@id

Handy functions

  • count(/library/book)
  • sum(/library/book/price)
  • string-length(title)
  • contains(title, 'XML')

Examples

Working sample

XML

<library>
  <book id="b1"><title>XML</title><price>499</price></book>
  <book id="b2"><title>XSLT</title><price>599</price></book>
</library>

Queries

  • Titles → /library/book/title
  • Expensive books → /library/book[price > 550]
  • Price of b2 → //book[@id='b2']/price/text()
  • Count → count(/library/book)
  • Sort-like selection → /library/book[1] (first), /library/book[last()] (last)

Self-check

Real-World Use

Do-now exercises

  • Write 10 XPath queries against your project XML and verify them in an online tester.
  • Use predicates for both value filters and positional filters.
  • Try an axis you rarely use (following-sibling or ancestor) and note the result.

📝 For exams

What examiners like

  • Define predicate with an example.
  • Explain two axes and where they are useful.
  • Show one function that returns a number and one that returns a string.

✨ Key points

Takeaways

  • XPath is context-sensitive; always know your current node.
  • Predicates and axes together unlock precise navigation.
  • Practice writing and reading XPath faster than memorizing it.