XPath basics
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>| Expression | Selects |
|---|---|
/library | the root element library |
/library/book | book children of the root |
//title | every 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>@idselects theidattribute,[@id='b2']is a predicate: it keeps only books whose id isb2,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.