Easy Tutorial
❮ Home Xpath Nodes ❯

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 following examples:

"books.xml":

View this "books.xml" file in your browser.


Loading XML Documents

All modern browsers support the method of loading XML documents using XMLHttpRequest.

Code for most modern browsers:

Code for old Microsoft browsers (IE 5 and 6):


Selecting Nodes

Unfortunately, Internet Explorer handles XPath differently than other browsers.

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:


Selecting All Titles

The following example selects all title nodes:

Example


Selecting the Title of the First Book

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

Example

There is an issue. The above example outputs different results in IE and other browsers.

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

A Solution!

To resolve the issue of [0] and [1] in IE5+, you can set the language selection (SelectionLanguage) for XPath.

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

Example


Selecting All Prices

The following example selects all text in price nodes:

Example


Selecting Price Nodes Greater Than 35

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

Example


Selecting Title Nodes with Price Greater Than 35

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

Example

❮ Home Xpath Nodes ❯