Xpath Syntax in XML
XPath Syntax in XML
What is XPath Syntax?
XPath syntax defines how to write expressions to navigate and select nodes in an XML document.
Basic Components of XPath Syntax
| Syntax Part | Description | Example |
|---|---|---|
/ | Select from the root node | /library/book selects all <book> under root <library> |
// | Select nodes from anywhere in the document | //title selects all <title> nodes anywhere |
nodeName | Select nodes with the given name | book selects all <book> nodes in the current context |
@attribute | Select attribute nodes | @category selects the category attribute |
. | Current node | . refers to the current node |
.. | Parent node | .. selects the parent of the current node |
* | Wildcard to select all nodes | book/* selects all child elements of <book> |
[condition] | Predicate to filter nodes | book[@category='fiction'] selects books with category 'fiction' |
text() | Select text content of a node | title/text() selects the text inside <title> |
Examples
Given this XML:
<library> <book category="fiction"> <title>The Hobbit</title> </book> <book category="history"> <title>Sapiens</title> </book></library>| XPath Expression | Meaning | Result |
|---|---|---|
/library/book | Select all <book> elements inside <library> | Both book nodes |
//title | Select all <title> elements anywhere | Both title nodes |
/library/book[@category='fiction'] | Select books with category = fiction | The Hobbit book |
/library/book/title/text() | Select the text inside all <title> nodes | "The Hobbit", "Sapiens" |
/library/book[1] | Select the first <book> element | The first book node |
/library/book[last()] | Select the last <book> element | The second book node |
Summary
XPath syntax uses path-like expressions to navigate XML nodes.
Predicates (
[...]) filter nodes by conditions.Wildcards and functions (like
text()) help target specific nodes or values.
Want me to help you write XPath queries or explain more about XPath functions?