XPath Examples

Toggle navigation
TUTORIAL HOME
XPath Examples
❮ Previous Next ❯
Let’s try to learn some basic XPath syntax by looking at some examples.

The 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 the “books.xml” file in your browser.

Loading the XML Document
Using an XMLHttpRequest object to load XML documents is supported in all modern browsers.

var xmlhttp = new XMLHttpRequest();
Code for older browsers (IE5 and IE6) can be found in the AJAX tutorial.

Selecting Nodes
Unfortunately, there are different ways of dealing with XPath in different browsers.

Chrome, Firefox, Edge, Opera, and Safari use the evaluate() method to select nodes:

xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE,null);
Internet Explorer uses the selectNodes() method to select node:

xmlDoc.selectNodes(xpath);
In our examples we have included code that should work with most major browsers.

Select all the titles
The following example selects all the title nodes:

Example
/bookstore/book/title
»
Select 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
»
Select all the prices
The following example selects the text from all the price nodes:

Example
/bookstore/book/price[text()]
»
Select price nodes with price>35
The following example selects all the price nodes with a price higher than 35:

Example
/bookstore/book[price>35]/price
»
Select title nodes with price>35
The following example selects all the title nodes with a price higher than 35:

Example
/bookstore/book[price>35]/title
»

❮ Previous Next ❯

Leave a comment