What is XPath?

XPath is a small query language for picking parts out of an XML document. An expression such as //book/title walks the document's tree of elements and returns every title inside a book, wherever it sits. XPath is used in XSLT stylesheets, XML Schema, Selenium and Playwright tests, web scrapers, and the configuration of many tools that read XML.

How to use the tester

  1. Type an XPath expression, like //book[price > 15]/title.
  2. Paste your XML below it.
  3. The results update as you type. A typing mistake in the expression or the XML shows what went wrong and, for the XML, the line and column where it happened.

Reading the results

  • An expression that selects nodes lists every match in document order, with its kind: an element shows as indented XML, an attribute as name="value", and text, CDATA and comments as their text. The Matches field counts them, and its copy button copies all of them, one per line.
  • An expression that computes something, like count(//book) or contains(//title, 'Garden'), shows its single value: a number, a string or a boolean (true or false).
  • Text that is only spaces and line breaks, which sits between elements in indented XML, is labelled as such so you can tell it apart from an empty result.

Namespaces

Prefixes the XML declares, like media in xmlns:media="…", work in the expression as they are: //media:thumbnail.

A default namespace, declared as xmlns="…" without a prefix, is the usual stumbling block. In XPath 1.0 a name without a prefix only matches elements in no namespace at all, so //entry finds nothing in an Atom feed. The tester gives each default namespace the prefix ns (then ns2, ns3 for more), so //ns:entry works. You can also match an element by its name alone with //*[local-name()='entry']. The Namespace prefixes table lists every prefix you can use.

Examples

With the sample library of books:

  • //book/title selects the three title elements.
  • //book[@genre='garden']/title/text() selects the titles of the garden books as text.
  • //book/@id selects the id attributes.
  • //book[price > 15]/title selects the titles of books over 15.
  • count(//book) returns 3.
  • sum(//price) returns 51.75.
  • string(//book[last()]/author) returns the last book's author.

How it works

The XML is read with the xmldom parser and the expression is evaluated by the xpath library, which implements XPath 1.0 with all of its functions and axes. Both run in your browser, so the XML never leaves your device.

Features

  • XPath 1.0 expressions with predicates, axes and functions
  • Elements, attributes, text, comments and computed values
  • Automatic namespace prefixes, including one for a default namespace
  • Error messages with the line and column of a mistake in the XML
  • Copy all matches at once
  • Runs in your browser