XML
Beginner
2 min read
XPath Syntax and Location Paths
Example
<?xml version="1.0" encoding="UTF-8"?>
<!--
Sample document used in XPath examples below
-->
<library xmlns:dc="http://purl.org/dc/elements/1.1/">
<book id="b001" category="fiction" lang="en">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
<price>12.99</price>
<dc:subject>American literature</dc:subject>
</book>
<book id="b002" category="non-fiction" lang="en">
<title>Clean Code</title>
<author>Robert C. Martin</author>
<year>2008</year>
<price>35.00</price>
</book>
<magazine id="m001" category="tech">
<title>Linux Journal</title>
<year>2024</year>
</magazine>
</library>
<!--
XPath Expressions (results annotated):
/library → root <library> element
/library/book → both <book> elements
//title → all <title> elements (book + magazine)
//book[@category='fiction'] → b001 only
//book[year > 2000] → b002 only
//book[@category='fiction']/title → <title>The Great Gatsby</title>
/library/* → book, book, magazine
/library/book[1] → first book (b001)
/library/book[last()] → last book (b002)
/library/book/@id → b001, b002 (attribute nodes)
count(//book) → 2
sum(//price) → 47.99
//book[not(@lang)] → none (both have lang)
/library/book[position() <= 2] → b001, b002
//title[contains(text(),'Code')] → Clean Code
-->