</>
Skip to content
XML lessons (12/29)

XML — XPath

Basic XPath

/bookstore/book           # All books
/bookstore/book[1]        # First book
/bookstore/book[last()]   # Last book

XPath Syntax

ExpressionDescription
nodenameAll 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

AxisDescription
ancestorAll ancestors
ancestor-or-selfAncestors + current
childDirect children
descendantAll descendants
followingAll following nodes
precedingAll preceding nodes
selfCurrent node

Functions

FunctionDescription
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

  1. Write basic XPath expressions
  2. Use predicates to filter
  3. Use axes to navigate
  4. 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.