Lesson 8 — Querying XML
XPath Basics
XPath is a query language for navigating an XML document's tree structure and selecting specific elements or values, similar to how a file path navigates a folder structure.
Basic XPath Syntax
An XPath expression reads much like a file system path, using slashes to move between levels of the tree, and can select elements based on their attributes.
XPath — Selecting elements
/library/book Select every <book> directly under <library>
/library/book/title Select every <title> inside a <book>
//title Select every <title> anywhere in the document
/library/book[@id='2'] Select the <book> with an id attribute of "2"
/library/book[1] Select the first <book> element
Common Mistakes
- Confusing a single slash (/) — direct child — with a double slash (//) — any descendant at any depth.
- Forgetting that XPath indices are 1-based (the first item is [1]), not 0-based like most programming languages.
- Writing an attribute selector without the @ symbol, e.g. book[id='2'] instead of book[@id='2'].
- Assuming XPath expressions are case-insensitive — they are case-sensitive, matching XML's own case sensitivity.
Professional Tip
Unlike most programming languages, XPath indices start at 1, not 0. This is a common source of off-by-one errors for developers coming from a typical programming background.
Your Turn
Given the library XML from the tree structure lesson, write XPath expressions to select all book titles, and to select only the second book element.
Mini Quiz
What does the // syntax mean in an XPath expression?
A double slash (//) searches for matching elements at any depth in the document, unlike a single slash (/) which only selects direct children.