CodeMIRAI
0 XP

XPath basics

2 min read 4 runnable examples Quiz included

XPath is a language for finding parts of an XML document, the way a file path finds a file. Many tools use it: XSLT, Selenium tests, Python's lxml, and browser developer tools.

On CodeMIRAI, put XPath expressions in comments starting with xpath: at the top of the document and press Run; each one is evaluated and its matches are listed.

Paths

XML
<!-- xpath: /library/book/title -->
<!-- xpath: //author -->
<library>
  <book id="b1">
    <title>Clean Code</title>
    <author>Robert C. Martin</author>
    <price>32.50</price>
  </book>
  <book id="b2">
    <title>The Pragmatic Programmer</title>
    <author>Andrew Hunt</author>
    <price>28.00</price>
  </book>
</library>
librarybook @id="b1"book @id="b2"titleauthortitleauthor/library/book/title selects both title elements
XPath walks the tree like folders: each / steps down one level. //title would find titles at any depth.
ExpressionSelects
/librarythe root element library
/library/bookbook children of the root
//titleevery title, at any depth
. / ..the current node / its parent
*any element

Attributes and text

XML
<!-- xpath: //book/@id -->
<!-- xpath: //book[@id='b2']/title/text() -->
<library>
  <book id="b1"><title>Clean Code</title></book>
  <book id="b2"><title>The Pragmatic Programmer</title></book>
</library>
  • @id selects the id attribute,
  • [@id='b2'] is a predicate: it keeps only books whose id is b2,
  • text() selects the text inside an element.

Predicates and positions

XML
<!-- xpath: //book[1]/title -->
<!-- xpath: //book[last()]/title -->
<!-- xpath: //book[price < 30]/title -->
<library>
  <book><title>Clean Code</title><price>32.50</price></book>
  <book><title>The Pragmatic Programmer</title><price>28.00</price></book>
  <book><title>Refactoring</title><price>41.00</price></book>
</library>

XPath counts from 1, not 0. last() is the last match, and predicates can compare values: [price < 30].

Functions

XML
<!-- xpath: count(//book) -->
<!-- xpath: sum(//price) -->
<!-- xpath: //title[contains(., 'Code')] -->
<library>
  <book><title>Clean Code</title><price>32.50</price></book>
  <book><title>Code Complete</title><price>35.00</price></book>
  <book><title>Refactoring</title><price>41.00</price></book>
</library>
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.