Test XPath expressions against XML documents
Common XPath Patterns:
//element - All elements with name/root/child - Direct child path//element[@attr='value'] - Element with attribute//element[position()=1] - First element//element/text() - Text contentXPath tester evaluates XPath expressions against XML documents to query and navigate XML trees. XPath is a powerful query language for selecting nodes, filtering by attributes, traversing relationships, and extracting data from XML.
Parse XML into DOM tree, then evaluate XPath expression. Navigate using axes (child, parent, ancestor, following-sibling), predicates ([condition]), functions (text(), contains(), count()). Return matching node set or value.
XPath 1.0 is widely supported, 2.0/3.0 add more features. Node types: element, attribute, text, comment, processing-instruction. Axes: child, parent, ancestor, descendant, following, preceding, self. Return types: node-set, string, number, boolean.
Extract specific elements from XML.
//book[@category="tech"]/titleSelect HTML elements by structure.
//div[@class="content"]//pTest selectors before using in stylesheets.
Query XML configuration files.
/config/database/host// Browser XPath API
const xml = `<library>
<book category="tech" available="true">
<title>JavaScript Guide</title>
<author>John</author>
<price>29.99</price>
</book>
<book category="fiction" available="false">
<title>The Story</title>
<author>Jane</author>
<price>19.99</price>
</book>
</library>`;
const parser = new DOMParser();
const doc = parser.parseFromString(xml, 'text/xml');
// Evaluate XPath
function xpath(expr, context = doc) {
const result = doc.evaluate(
expr, context, null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);
const nodes = [];
for (let i = 0; i < result.snapshotLength; i++) {
nodes.push(result.snapshotItem(i));
}
return nodes;
}
// Examples
xpath('//book/title'); // All titles
xpath('//book[@category="tech"]'); // Tech books
xpath('//book[price>20]/title'); // Titles of books over $20
xpath('//book[@available="true"]/author'); // Authors of available books
xpath('count(//book)'); // Number of books (use NUMBER_TYPE)
// Get text content
xpath('//book[1]/title')[0].textContent; // "JavaScript Guide"Browser native XPath evaluation. For Node.js, use xmldom with xpath package.
Use XPath tester when parsing XML, testing XPath expressions for XSLT, web scraping HTML, or learning XPath syntax.
/ selects direct children only. // selects descendants at any depth (descendant-or-self). //title finds all title elements anywhere, /root/title finds only direct children of root.