From http://www.w3schools.com (Copyright Refsnes Data)
| « Previous | Next Chapter » |
Let's try to learn some basic XPath syntax by looking at some examples.
We will use the following XML document in the examples below.
"books.xml":
|
<?xml version="1.0" encoding="ISO-8859-1"?> <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 the "books.xml" file in your browser.
Using XMLHttpRequest to load XML documents is supported in all modern browsers.
Code for most modern browsers:
| var xmlhttp=new XMLHttpRequest() |
Code for old Microsoft browsers (IE 5 and 6):
| var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") |
Unfortunately, there are different ways of dealing with XPath in Internet Explorer and other browsers.
In our examples we have included code that should work with most major browsers.
Internet Explorer uses the selectNodes() method to select nodes from the XML document:
| xmlDoc.selectNodes(xpath); |
Firefox, Chrome, Opera and Safari use the evaluate() method to select nodes from the XML document:
| xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE,null); |
The following example selects all the title nodes:
Example
Try it yourself » |
The following example selects the title of the first book node under the bookstore element:
Example
Try it yourself » |
There is a problem with this. The example above shows different results in IE and other browsers.
IE5 and later has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!!
To solve the [0] and [1] problem in IE5+, you can set the SelectionLanguage to XPath.
The following example selects the title of the first book node under the bookstore element:
Example
Try it yourself » |
The following example selects the text from all the price nodes:
Example
Try it yourself » |
The following example selects all the price nodes with a price higher than 35:
Example
Try it yourself » |
The following example selects all the title nodes with a price higher than 35:
Example
Try it yourself » |
| « Previous | Next Chapter » |
From http://www.w3schools.com (Copyright Refsnes Data)