XML and XPath
What is XPath?
XPath is a major element in the XSLT standard.
XPath can be used to locate (navigate) elements and attributes in an XML document.
XPath

- XPath is used to define the syntax of various parts of an XML document
- XPath uses path expressions to navigate in an XML document
- XPath includes a standard function library
- XPath is a major element in XSLT and XQuery
- XPath is a W3C recommended standard
XPath Path Expressions
XPath uses path expressions to select nodes or node sets in an XML document. These path expressions look very similar to the expressions you see when using a traditional computer file system.
XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C, C++, and many other languages.
XPath is used in XSLT
XPath is a major element in the XSLT standard.
Once you understand XPath, you can fully utilize XSL.
XPath Examples
We will use the following XML document:
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="美食"> <title lang="zh">雅舍谈吃</title> <author>梁实秋</author> <year>2013</year> <price>35</price> </book> <book category="children"> <title lang="en">Fantastic Mr. Fox</title> <author>Roald Dahl</author> <year>2009</year> <price>10.00</price> </book> <book category="literature"> <title lang="en">Making the Familiar Strange</title> <author>Zygmunt Bauman</author> <author>Peter Haffner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="politics"> <title lang="en">Democracy in America</title> <author>托克维尔</author> <year>1989</year> <price>60.00</price> </book> </bookstore>
In the table below, we list some XPath expressions and their results:
XPath Expressions | Results |
---|---|
/bookstore/book[1] | Select the first book element that is a child element of the bookstore element. |
/bookstore/book[last()] | Select the last book element that is a child element of the bookstore element. |
/bookstore/book[last()-1] | Select the second-to-last book element that is a child element of the bookstore element. |
/bookstore/book[position()<3] | Select the first two book elements that are child elements of the bookstore element. |
//title[@lang] | Select all title elements that have an attribute named 'lang'. |
//title[@lang='en'] | Select all title elements that have an attribute 'lang' with the value 'en'. |
/bookstore/book[price>35.00] | Select all book elements within the bookstore element where the value of the price element is greater than 35.00. |
/bookstore/book[price>35.00]/title | Select all title elements with a price element value greater than 35.00 within the book element of the bookstore element. |
XPath Tutorial
You will learn about XPath For More Knowledge.