ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

XML Tutorial• 7 min read

XPath: Querying & Navigating XML Nodes

Path expressions, absolute vs relative paths, predicates, and functions

XPath (XML Path Language) uses path expressions to navigate through elements and attributes in an XML document, functioning like SQL for hierarchical XML trees.

Key XPath Syntax Patterns

/: Selects from the root node (absolute path).

//: Selects nodes across the document from the current node that match the selection no matter where they are.

@: Selects attributes (e.g., //book/@id).

[] (Predicates): Filters nodes by conditional criteria (e.g. //book[price > 35], //book[last()]).

*: Wildcard matching any element node.

Common XPath Query Expressions
// 1. Select all titles anywhere in the document
//title

// 2. Select the first book in the bookstore
/bookstore/book[1]

// 3. Select all books with price greater than 30.00
//book[price > 30.00]

// 4. Select the category attribute of all books
//book/@category

// 5. Select books published in year 2024 with English language
//book[year=2024 and @lang='en']
XPath expressions concisely isolate exact XML subtrees.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which XPath expression selects all `<price>` elements anywhere in an XML document regardless of nesting depth?