Xpath Examples in XML
XPath Examples in XML
Given this sample XML:
<library> <book id="b1" category="fiction"> <title lang="en">The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <year>1925</year> </book> <book id="b2" category="history"> <title lang="en">Sapiens</title> <author>Yuval Noah Harari</author> <year>2011</year> </book> <book id="b3" category="fiction"> <title lang="fr">Le Petit Prince</title> <author>Antoine de Saint-Exupéry</author> <year>1943</year> </book></library>XPath Query Examples and Results
| XPath Expression | Meaning | Result Node(s) |
|---|---|---|
/library/book | Select all <book> elements under <library> | All 3 <book> elements |
/library/book[1] | Select the first <book> element | <book id="b1" ...> |
//title | Select all <title> elements anywhere | All 3 <title> elements |
//book[@category='fiction'] | Select all <book> elements with category "fiction" | Books with id b1 and b3 |
//book/title[@lang='en'] | Select <title> elements where lang="en" | Titles: "The Great Gatsby", "Sapiens" |
//book[author='Yuval Noah Harari'] | Select <book> where author is "Yuval Noah Harari" | <book id="b2" ...> |
//book[year>1950] | Select <book> published after 1950 | <book id="b2" ...> |
/library/book/title/text() | Select text content of all <title> | "The Great Gatsby", "Sapiens", "Le Petit Prince" |
Using XPath Axes Examples
| XPath Expression | Meaning | Result |
|---|---|---|
/library/book/title/parent::book | Select parent <book> of each <title> | The <book> elements |
/library/book[1]/following-sibling::book | Select books after the first book | Books with id b2 and b3 |
/library/book[2]/preceding-sibling::book | Select books before the second book | Book with id b1 |
//title/ancestor::library | Select the <library> ancestor of all <title> | The <library> root node |
If you'd like, I can help you construct XPath expressions tailored to your XML data!