TExcelTAD
Home › XML › XML XPath

XML XPath

XPath is a small language for selecting parts of an XML document. An XPath expression describes a path through the tree, much like a file path describes a route through folders. It is used by XSLT, XQuery, XML Schema, test tools, web scrapers — and you can run it directly in the browser with document.evaluate.

All examples on this page use this café menu:

xml · try it yourself
<menu>
  <item type="drink" vegan="yes"><name>Espresso</name><price>2.20</price></item>
  <item type="drink" vegan="no"><name>Latte</name><price>3.40</price></item>
  <item type="food" vegan="yes"><name>Hummus wrap</name><price>6.90</price></item>
  <item type="food" vegan="no"><name>Croque monsieur</name><price>7.50</price></item>
  <item type="dessert" vegan="no"><name>Cheesecake</name><price>4.80</price></item>
</menu>

Path syntax

Expression Selects
/menu The root element menu
/menu/item All item children of menu
//name All name elements anywhere in the document
/menu/item/@type The type attribute of every item
. / .. The current node / its parent
* Any element
@* Any attribute
text() Text nodes

Predicates

Square brackets filter a step:

Expression Selects
/menu/item[1] The first item (XPath counts from 1!)
/menu/item[last()] The last item
//item[@type='food'] Items whose type is food
//item[price > 4] Items with a price above 4
//item[@vegan='yes']/name Names of vegan items
//item[position() <= 2] The first two items
//item[contains(name, 'e')] Items whose name contains "e"

Running XPath in the browser

doc.evaluate(expression, contextNode, nsResolver, resultType, result) runs an expression. The result type decides what you get back:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<menu>
      <item type="drink" vegan="yes"><name>Espresso</name><price>2.20</price></item>
      <item type="drink" vegan="no"><name>Latte</name><price>3.40</price></item>
      <item type="food" vegan="yes"><name>Hummus wrap</name><price>6.90</price></item>
      <item type="food" vegan="no"><name>Croque monsieur</name><price>7.50</price></item>
      <item type="dessert" vegan="no"><name>Cheesecake</name><price>4.80</price></item>
    </menu>`;
    const doc = new DOMParser().parseFromString(xml, 'application/xml');

    // Helper: return all matching nodes as an array
    function select(expr) {
      const r = doc.evaluate(expr, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      const out = [];
      for (let i = 0; i < r.snapshotLength; i++) out.push(r.snapshotItem(i));
      return out;
    }

    console.log('All names:', select('//name').map(n => n.textContent).join(', '));
    console.log('Vegan:', select("//item[@vegan='yes']/name").map(n => n.textContent).join(', '));
    console.log('Over 4:', select('//item[price > 4]/name').map(n => n.textContent).join(', '));
    console.log('Second item:', select('/menu/item[2]/name')[0].textContent);
    console.log('Types:', select('//item/@type').map(a => a.value).join(', '));
  </script>
</body>
</html>

Functions and non-node results

XPath can also compute numbers, strings and booleans:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<menu>
      <item type="drink"><name>Espresso</name><price>2.20</price></item>
      <item type="drink"><name>Latte</name><price>3.40</price></item>
      <item type="food"><name>Hummus wrap</name><price>6.90</price></item>
    </menu>`;
    const doc = new DOMParser().parseFromString(xml, 'application/xml');
    const num = (e) => doc.evaluate(e, doc, null, XPathResult.NUMBER_TYPE, null).numberValue;
    const str = (e) => doc.evaluate(e, doc, null, XPathResult.STRING_TYPE, null).stringValue;
    const bool = (e) => doc.evaluate(e, doc, null, XPathResult.BOOLEAN_TYPE, null).booleanValue;

    console.log('count(//item)       =', num('count(//item)'));
    console.log("sum(//price)        =", num('sum(//price)').toFixed(2));
    console.log("string(//item[3]/name) =", str('string(//item[3]/name)'));
    console.log("upper first name    =", str("translate(//item[1]/name, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')"));
    console.log("any food?           =", bool("boolean(//item[@type='food'])"));
  </script>
</body>
</html>
Result type Read with
XPathResult.NUMBER_TYPE .numberValue
XPathResult.STRING_TYPE .stringValue
XPathResult.BOOLEAN_TYPE .booleanValue
XPathResult.FIRST_ORDERED_NODE_TYPE .singleNodeValue
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE .snapshotLength, .snapshotItem(i)

Note: Browsers implement XPath 1.0. Newer versions (2.0, 3.1) add regular expressions, dates and sequences, but they need a library or a server-side processor such as Saxon.

Axes

Steps can move in any direction, not only down. The full form is axis::test:

Axis Example Meaning
child:: child::item (same as item) Children
descendant:: descendant::name All descendants
parent:: parent::* (same as ..) The parent
ancestor:: ancestor::menu All ancestors
following-sibling:: following-sibling::item[1] The next sibling item
preceding-sibling:: preceding-sibling::item Earlier sibling items
attribute:: attribute::type (same as @type) Attributes

For example //item[name='Latte']/following-sibling::item[1]/name selects the name of the item right after the latte: Hummus wrap.

Tip: XPath also works on the HTML page itself: in the browser console try $x('//h2') (Chrome/Firefox DevTools shortcut) to list every second-level heading.

Test yourself

What does //item[1] select first in XPath — the first or second item?

  1. The second, because counting starts at 0
  2. The first, because XPath positions start at 1
  3. All items
  4. Nothing — [1] is invalid

Which expression selects the type attribute of every item?

  1. //item/type
  2. //item[@type]
  3. //item/@type
  4. //@item/type

Which result type gives you a number from count(//item)?

  1. XPathResult.NUMBER_TYPE
  2. XPathResult.STRING_TYPE
  3. XPathResult.ANY_UNORDERED_NODE_TYPE
  4. XPathResult.SNAPSHOT_TYPE