XPath Examples

Books.xml:




  
    ABC
    Author Name
    2020
    29.99
  

  
    XQuery Book
    Author 1
    Author 2
 
 2005
    49.99
  


Loading the XML Document:

To load the XML documents, we can use an XMLHttpRequest object. All modern browsers support it.

Example:

var xmlhttp = new XMLHttpRequest();

Selecting Nodes:

In different browsers, there are different ways of dealing with XPath.

Chrome, Firefox, Edge, Opera, and Safari:

They use the evaluate() method to select nodes.

Syntax:

xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE,null);

Internet Explorer:

It uses the selectNodes() method to select a node.

Syntax:

xmlDoc.selectNodes(xpath);

Select all the titles:

Example:





Output:

Explanation:

In the above example, we are selecting all the title nodes.

Select the title of the first book:

Example:





Output:

Explanation:

In the above example, we are selecting the title of the first book node under the bookstore element.

Select all the prices:

Example:





Output:

Explanation:

In the above example, we are selecting the text from all the price nodes.

Select price nodes with price>30.00:

Example:





Output:

Explanation:

In the above example, we are selecting all the price nodes with a price higher than 30.00.

Select price nodes with price<30.00:

Example:





Output:

Explanation:

In the above example, we are selecting all the price nodes with a price lower than 30.00.

Select title nodes with price<30.00:

Example:





Output:

Explanation:

In the above example, we are selecting all the title nodes with a price lower than 30.00.