Xpath in Javascript

Sayan Guha
3 min readNov 11, 2019

--

What is Xpath?

  • XPath is a syntax for defining parts of an XML document
  • XPath uses path expressions to navigate in XML documents
  • XPath contains a library of standard functions
  • XPath is a major element in XSLT and in XQuery
  • XPath is a W3C recommendation

Xpath Expressions:

XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system.

How do you write Xpath in Javascript?

We can break down how to write Xpath in 3 steps:

Step 1: First you need to load your XML into your DOM — To load your XML use the AJAX request for this. The code is taken from W3schools as follows:

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open(“GET”, “books.xml”, true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById(“demo”).innerHTML =
xmlDoc.getElementsByTagName(“title”)[0].childNodes[0].nodeValue;
}
</script>

Step 2: Use the Xpath evaluate expression. It is under document and the syntax is as follows:

var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );

But instead of document use the ‘xmlDoc’ element we created your expression should look like this:

var xpathResult = xmlDoc.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );

Define the xpathExpression as some string, lets say we want to get all the books title from “Books.xml” defined in w3schools here.

The XPath expression variable would be as follows:

var xpathExpression = "//book/title"

What if we want to get the “Book Title” as well as the “Author of the book”?

We can use the Union operator in Xpath which is this “|”

The Xpath for getting the book author would be:

var xpathExpression = "//book/author"

Now if we want to get the author and title we would use the Union operator (“|”). Your XPath expression would be :

var xpathExpression = "//book/author|//book/author"

More information on Xpath can be found here. You can aggregation functions such as sum, count as well which can be used to return numeric data.

Example for the sum of all the book prices in the XML is as follows:

var xpathExpression = "sum(//book/price)"

Step 3: Iterating through the result of the Xpath, the following code shows how to iterate through the XPath for finding all authors and titles of the books.

var iterator = xmlDoc.evaluate('//book/author|//book/author', documentNode, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null );

try {
var thisNode = iterator.iterateNext();

while (thisNode) {
alert( thisNode.textContent );
thisNode = iterator.iterateNext();
}
}
catch (e) {
alert( 'Error: Document tree modified during iteration ' + e );
}

Breaking the code down:

When the specified result type in the resultType the parameter is either:

  • UNORDERED_NODE_ITERATOR_TYPE
  • ORDERED_NODE_ITERATOR_TYPE

The XPathResult the object returned is a node-set of matched nodes which will behave as an iterator, allowing us to access the individual nodes contained by using the iterateNext() method of the XPathResult.

Once we have iterated over all of the individuals matched nodes, iterateNext() will return null.

The value of the result is saved in thisNode.textContent. The value can also be retrieved by using the result.childNodes[0].nodeValue.

You can now use the data to populate in your HTML.

You can run XML queries and see the output in this link.

--

--