What is XPath in XML?

Estimated study time: 13 minutes.

XPath (XML Path Language) is a query language for selecting nodes from an XML document. Instead of writing custom code to walk the tree, you describe a path, and XPath finds every element or attribute that matches it.

A Simple Example

<course>
  <modules>
    <module>Excel Basics</module>
    <module>SQL for Analysis</module>
  </modules>
</course>
/course/modules/module

This XPath expression selects every module element nested inside modules inside the root course element — returning both module nodes.

Why XPath Matters

  • It's the addressing system XSLT uses to select which parts of a document to transform.
  • It powers node selection in most XML-processing libraries and tools.
  • The same path syntax works consistently across many technologies (XSLT, XQuery, and testing tools).

Where You'll See XPath

  • Inside XSLT stylesheets, to select which nodes to transform.
  • In test automation tools, to locate elements in an HTML/XML DOM.
  • In XML-processing libraries like lxml in Python.
💡 Tip: Think of XPath as a "file path for XML" — once you're comfortable navigating folders with / and .., XPath's syntax will feel familiar.

Reading an XPath Expression Piece by Piece

An XPath expression is a series of steps separated by slashes. Each step can have three parts: an axis (which direction to move), a node test (which nodes to match) and optional predicates in square brackets (extra filters). Consider this document:

<library>
  <book id="b1" lang="en">
    <title>Learning SQL</title>
    <price>450</price>
  </book>
  <book id="b2" lang="hi">
    <title>Python Basics</title>
    <price>300</price>
  </book>
</library>

Here are some expressions and what they return:

ExpressionResult
/library/book/titleBoth title elements
//titleEvery title anywhere in the document
//book[@lang='hi']/titleThe title of the Hindi book only
//book[price > 400]/titleTitles of books priced above 400
//book[1]The first book child of its parent (XPath counts from 1)
//book/@idThe id attributes, not the elements
count(//book)The number 2

Useful Axes and Functions

Most day-to-day XPath uses the shorthand /, //, ., .. and @. When you need more control, the full axes help:

  • parent:: and ancestor:: move upward through the tree.
  • following-sibling:: and preceding-sibling:: move sideways at the same level.
  • descendant:: searches everything below the current node.

Common functions include text() for the text content, contains() and starts-with() for partial matches, and last() for the final item in a set, as in //book[last()].

Running XPath in Python with lxml

from lxml import etree

tree = etree.parse("library.xml")

titles = tree.xpath("//book[@lang='en']/title/text()")
print(titles)          # ['Learning SQL']

total = tree.xpath("sum(//price)")
print(total)           # 750.0

Notice that a path ending in text() returns strings, while a path ending in an element name returns element objects you can explore further. Functions such as sum() and count() return a single number instead of a list.

Before putting an expression into a script, test it interactively. Browser developer tools accept XPath through $x("//title") in the console, and many code editors include an XPath evaluator for XML files. Trying a path on real data first saves a lot of debugging later.

Common XPath Mistakes

  • Overusing //. It searches the whole tree, which is slower on big files and may match nodes you did not intend.
  • Forgetting namespaces. If the document declares a default namespace, //book may return nothing. You must register a prefix and write //ns:book.
  • Counting from zero. Positions start at 1, so book[0] matches nothing.
  • Mixing up attributes and elements. @id is an attribute; id without the at sign looks for a child element.
  • Brittle absolute paths in test automation. A path like /html/body/div[3]/div[2]/a breaks with any layout change. Prefer stable attributes, for example //a[@data-test='login'].

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with the Data Analytics Course at Uncodemy.

Explore XML Course →