XPath Examples
In this section, let's learn some basic XPath syntax through examples.
XML Example Document
We will use this XML document in the examples below:
"books.xml":
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
View this "books.xml" file in your browser。
Load XML Document
All modern browsers support the method of using XMLHttpRequest to load XML documents.
Code for most modern browsers:
Code for legacy Microsoft browsers (IE 5 and 6):
Select Nodes
Unfortunately, Internet Explorer handles XPath differently from others.
In our examples, we include code that works for most major browsers.
Internet Explorer uses the selectNodes() method to select nodes from an XML document:
Firefox, Chrome, Opera, and Safari use the evaluate() method to select nodes from an XML document:
Select All title
The following example selects all title nodes:
Select the title of the first book
The following example selects the title of the first book node under the bookstore element:
There is a problem here. The example above outputs different results in IE and other browsers.
IE5 and later versions treat
A Workaround!
To solve the
The following example selects the title of the first book node under the bookstore element:
Example
xml.selectNodes("/bookstore/book[1]/title");
Try it Yourself »
Select All Prices
The following example selects all text in the price nodes:
Select price nodes with price higher than 35
The following example selects all price nodes with price higher than 35:
Select title nodes with price higher than 35
The following example selects all title nodes with price higher than 35:
Other Extensions