Xpath Examples
## XPath Examples
* * *
In this section, let's learn some basic XPath syntax through examples.
* * *
## XML Example Document
We will use the following XML document in the examples below:
"books.xml":
Everyday Italian
Giada De Laurentiis
2005
30.00
Harry Potter
J K. Rowling
2005
29.99
XQuery Kick Start
James McGovern
Per Bothner
Kurt Cagle
James Linn
Vaidyanathan Nagarajan
2003
49.99
Learning XML
Erik T. Ray
2003
39.95
[View this "books.xml" file in your browser](#).
* * *
## Loading XML Documents
All modern browsers support loading XML documents using XMLHttpRequest.
Code for most modern browsers:
var xmlhttp=new XMLHttpRequest()
Code for older Microsoft browsers (IE 5 and 6):
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
* * *
## Selecting Nodes
Unfortunately, Internet Explorer handles XPath differently from other browsers.
In our examples, we include code compatible with most mainstream browsers.
Internet Explorer uses the selectNodes() method to select nodes from an XML document:
xmlDoc.selectNodes(_xpath_);
Firefox, Chrome, Opera, and Safari use the evaluate() method to select nodes from an XML document:
xmlDoc.evaluate(_xpath_, xmlDoc, null, XPathResult.ANY_TYPE,null);
* * *
## Select All title Elements
The following example selects all title nodes:
## Example
/bookstore/book/title
[Try it yourself Β»](#)
* * *
## Select the title of the First book
The following example selects the title of the first book element under the bookstore element:
## Example
/bookstore/book/title
[Try it yourself Β»](#)
There is an issue here. The above example produces different results in IE and other browsers.
IE5 and later treat as the first node, whereas according to the W3C standard, it should be .
### A Solution!
To resolve the vs issue in IE5+, you can set the SelectionLanguage property for XPath.
The following example selects the title of the first book element under the bookstore element:
## Example
_xml_.setProperty("SelectionLanguage","XPath");
_xml_.selectNodes("/bookstore/book/title");
[Try it yourself Β»](#)
* * *
## Select All price Text Content
The following example selects all text content within price nodes:
## Example
/bookstore/book/price/text()
[Try it yourself Β»](#)
* * *
## Select price Nodes Where Price > 35
The following example selects all price nodes where the price is greater than 35:
## Example
/bookstore/book[price>35]/price
[Try it yourself Β»](#)
* * *
## Select title Nodes Where Price > 35
The following example selects all title nodes where the price is greater than 35:
## Example
/bookstore/book[price>35]/title
[Try it yourself Β»](#)
YouTip