XML — XPath
Basic XPath
/bookstore/book # All books
/bookstore/book[1] # First book
/bookstore/book[last()] # Last book
XPath Syntax
| Expression | Description |
|---|---|
| nodename | All nodes |
| / | Root node |
| // | Any node |
| . | Current node |
| .. | Parent node |
| @ | Attribute |
Predicates
/bookstore/book[1] # First book
/bookstore/book[last()] # Last book
/bookstore/book[position()<3] # First 2 books
/bookstore/book[@genre='fiction'] # Fiction books
/bookstore/book[price>30] # Books over 30
Axes
| Axis | Description |
|---|---|
| ancestor | All ancestors |
| ancestor-or-self | Ancestors + current |
| child | Direct children |
| descendant | All descendants |
| following | All following nodes |
| preceding | All preceding nodes |
| self | Current node |
Functions
| Function | Description |
|---|---|
| count() | Count nodes |
| sum() | Sum values |
| text() | Text content |
| contains() | String contains |
| starts-with() | String starts with |
Using XPath in JavaScript
var result = xmlDoc.evaluate(
"/bookstore/book/title",
xmlDoc,
null,
XPathResult.ANY_TYPE,
null
);
Mini Practice
- Write basic XPath expressions
- Use predicates to filter
- Use axes to navigate
- Combine functions with XPath
Up Next
Continue with XQuery — querying XML data with XQuery.
Related Topics
Frequently Asked Questions about XPath
What is XPath in XML?
XPath is a fundamental concept in XML. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn XPath?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn XPath.
Why is XPath important in XML?
XPath is essential for XML development. Understanding this concept will help you write better code and solve real-world problems more effectively.