Python XPath Syntax, Predicates & Axes
XPath (XML Path Language) uses path expressions to select nodes or node-sets in an XML document. It supports absolute (/root) and relative (//child) paths, attribute selection (@attr), filtering predicates ([price > 30]), and directional axes (parent::, child::, following-sibling::).
"XPath is like a precise GPS navigation coordinate system for XML documents: instead of traversing line by line, you type a short path expression and jump directly to the exact target node anywhere in the tree."
Deep Dive: How It Works
Path Operators: / selects from the root; // selects matching nodes anywhere in the document; . is current node; .. is parent.
Attribute Selection: @id matches attribute named id.
Predicates ([...]): //book[price > 20] filters only books with price greater than 20; //book[1] selects the first book.
XPath Axes: ancestor::, descendant::, following-sibling::, parent:: navigate relative directions.
Syntax Blueprint
//book[@category="web"][price < 50]/title
Selects the <title> of all web category books whose price is under $50 anywhere in the tree.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Assuming XPath indices start at 0.Why it happens: In XPath, indexing starts at 1, not 0: //book[1] selects the first book, while //book[0] matches nothing.
How to fix: Remember that XPath uses 1-based indexing.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Write an XPath predicate for active users
Write the XPath expression that selects all `<username>` elements for users where attribute `@active="true"`.
Path format: `//user[@active="true"]/username`
Finished reading and practicing?
Mark this lesson as completed to update your course progress.