XPath Examples
In this section, let us learn by example to some basic XPath syntax.
XML instance documents
We will use this XML document in the following example:
"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 "books.xml" file in your browser .
Load an XML document
All modern browsers support the use of XMLHttpRequest to load XML documents.
For most modern browsers code:
For the old Microsoft browser (IE 5 and 6) of the Code:
Select node
Unfortunately, Internet Explorer and other different way of handling XPath.
In our example, it contained for most major browsers code.
Internet Explorer uses selectNodes () method from the XML document to select nodes:
Firefox, Chrome, Opera and Safari use the evaluate () method to select nodes from the XML document:
Select all title
The following examples select all title nodes:
Examples
Select the first title of a book
The following examples select bookstore element below the first book node title:
Examples
There is a problem. The above examples of different results in IE and other browsers.
IE5 and later the [0] regarded as the first node, and according to the W3C standards should be [1].
One solution!
In order to solve the IE5 + [0] and [1] of the problem, you can set the language selection for the XPath (SelectionLanguage).
The following examples select bookstore element below the first book node title:
Examples
xml.selectNodes("/bookstore/book[1]/title");
Select all prices
The following examples select all the text node price:
Examples
Select the price is higher than the price node 35
The following examples select all price higher than the price of 35 nodes:
Examples
Select the node price is higher than 35 title
The following examples select all the title nodes prices higher than 35: