Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

XPath Examples

XPath Examples


In this section let us learn some basic XPath syntax through examples.


XML example document

We will use this 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 an XML document

All modern browsers support loading XML documents with XMLHttpRequest.

Code for most modern browsers:

var xmlhttp=new XMLHttpRequest()

Code for old 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 example, code is included that works with most major 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);


Selecting all title nodes

The following example selects all title nodes:

Example

/bookstore/book/title

Try it »


Selecting the title of the first book

The following example selects the title of the first book node under the bookstore element:

Example

/bookstore/book[1]/title

Try it »

There is a problem here. The example above produces different results in IE and in other browsers.

IE5 and later treat [0] as the first node, while according to the W3C standard it should be [1].

One workaround!

To solve the [0] and [1] problem in IE5+, you can set the SelectionLanguage for XPath.

The following example selects the title of the first book node under the bookstore element:

Example

xml

.setProperty("SelectionLanguage","XPath");

xml

.selectNodes("/bookstore/book[1]/title");

Try it »


Selecting all prices

The following example selects all text in price nodes:

Example

/bookstore/book/price/text()

Try it »


Selecting price nodes with a price higher than 35

The following example selects all price nodes with a price higher than 35:

Example

/bookstore/book[price>35]/price

Try it »


Selecting title nodes with a price higher than 35

The following example selects all title nodes with a price higher than 35:

Example

/bookstore/book[price>35]/title

Try it »