Xpath in XML
XPath in XML
What is XPath?
XPath stands for XML Path Language.
It is a language used to navigate through elements and attributes in an XML document.
XPath is mainly used for selecting nodes or node-sets in XML.
Widely used in XML parsing, XSLT, and XML querying.
How XPath Works
XPath uses path expressions to select nodes.
Paths look similar to file system paths, using
/to navigate.
Basic XPath Syntax
| XPath Expression | Meaning |
|---|---|
/ | Selects the root node |
/bookstore/book | Selects all <book> elements that are children of <bookstore> |
//book | Selects all <book> elements anywhere in the document |
/bookstore/book[1] | Selects the first <book> element in <bookstore> |
//title[@lang='en'] | Selects all <title> elements with attribute lang equal to 'en' |
//book/title/text() | Selects the text content of all <title> elements under <book> |
Example XML Document
<bookstore> <book category="fiction"> <title lang="en">Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> </book> <book category="cooking"> <title lang="fr">Le Cordon Bleu</title> <author>Julia Child</author> <year>2000</year> </book></bookstore>Example XPath Queries
| XPath Query | Result |
|---|---|
/bookstore/book/title | Selects both <title> elements |
/bookstore/book[@category='fiction'] | Selects the <book> with category "fiction" |
//title[@lang='en'] | Selects <title lang="en">Harry Potter</title> |
//book[author='Julia Child']/title | Selects <title> of book where author is Julia Child |
//book/year/text() | Selects the year text nodes: 2005 and 2000 |
Summary
| Feature | Description |
|---|---|
| XPath | Language for selecting nodes in XML |
| Uses | XML parsing, querying, transformations |
| Syntax | Uses path expressions and predicates |
| Can select | Elements, attributes, text nodes, namespaces |
If you want, I can help you write XPath expressions or use XPath with your XML data!