XML XPath

XPath is a query language for addressing exact parts of an XML document using compact, path-like expressions instead of manual DOM traversal.

Why XPath Exists

Walking a document node-by-node with getElementsByTagName() and parentNode works, but it becomes verbose for anything beyond simple lookups — selecting "the second book's price" or "every author whose book costs more than 30" requires several lines of manual looping. XPath expresses these selections as a single string, similar in spirit to a file system path, letting a query engine do the traversal internally.

XPath treats an XML document as a tree of nodes, exactly like the DOM does, and a path expression describes a route through that tree, optionally narrowed by conditions in square brackets.

Core Path Syntax

  • / — selects from the document root, and separates steps in a path
  • // — selects matching nodes anywhere in the document, at any depth
  • . and .. — the current node, and its parent
  • @ — selects an attribute rather than an element, e.g. @id
  • [ ] — a predicate that filters nodes by position or condition, e.g. [1] or [price>30]
  • * — a wildcard that matches any element name

A few representative XPath expressions against a books document.

Sample expressions

<!DOCTYPE html>
<html>
<body>

<pre>
&lt;!--
Document:
&lt;catalog&gt;
  &lt;book category="fiction"&gt;
    &lt;title&gt;Night Watch&lt;/title&gt;
    &lt;price&gt;18.50&lt;/price&gt;
  &lt;/book&gt;
  &lt;book category="reference"&gt;
    &lt;title&gt;XML Essentials&lt;/title&gt;
    &lt;price&gt;34.00&lt;/price&gt;
  &lt;/book&gt;
&lt;/catalog&gt;
--&gt;

/catalog/book              -&gt; both &lt;book&gt; elements
/catalog/book[1]           -&gt; the first &lt;book&gt; (Night Watch)
//title                    -&gt; every &lt;title&gt; anywhere in the document
/catalog/book[@category='reference']  -&gt; the book with that attribute value
/catalog/book[price&gt;20]/title         -&gt; titles of books priced above 20
</pre>

</body>
</html>

Evaluating XPath in JavaScript

Browsers expose XPath evaluation through document.evaluate(), which takes the expression, a context node, an optional namespace resolver, a result type constant, and returns an XPathResult you iterate or read from.

Running an XPath query against a parsed XML document and iterating matches.

document.evaluate() in practice

<!DOCTYPE html>
<html>
<body>

<script>
const xml = `<catalog>
  <book><title>Night Watch</title><price>18.50</price></book>
  <book><title>XML Essentials</title><price>34.00</price></book>
</catalog>`;
const xmlDoc = new DOMParser().parseFromString(xml, "text/xml");

const result = document.evaluate(
  "//book[price>20]/title",
  xmlDoc,
  null,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null
);

for (let i = 0; i < result.snapshotLength; i++) {
  console.log(result.snapshotItem(i).textContent);
}
// "XML Essentials"
</script>

</body>
</html>

Selecting a single attribute value with XPath.

Selecting an attribute

<!DOCTYPE html>
<html>
<body>

<script>
const xml = `<catalog>
  <book category="fiction"><title>Night Watch</title><price>18.50</price></book>
  <book category="reference"><title>XML Essentials</title><price>34.00</price></book>
</catalog>`;
const xmlDoc = new DOMParser().parseFromString(xml, "text/xml");

const categoryResult = document.evaluate(
  "/catalog/book[1]/@category",
  xmlDoc,
  null,
  XPathResult.STRING_TYPE,
  null
);
console.log(categoryResult.stringValue); // "fiction"
</script>

</body>
</html>
Result Type ConstantUse When You Want
STRING_TYPEA single string value, like text or an attribute
NUMBER_TYPEA single numeric value
BOOLEAN_TYPEA true/false test result
ORDERED_NODE_SNAPSHOT_TYPEA static, indexable list of matched nodes
Note: XPath is not exclusive to JavaScript — it is also the addressing language used inside XSLT stylesheets and by many server-side XML libraries, so learning it once pays off across several tools.
Note: XPath indexing is 1-based, not 0-based. book[1] means the first book, and book[0] is not an error — it's simply a predicate that never matches anything, which can silently produce empty results if you forget the difference from array indexing.

Exercise: XML XPath

What is XPath primarily used for?