XPath expression support for finding and selecting elements within XML documents. ElementTree supports a subset of XPath expressions for element selection and filtering.
// Direct access to XPath implementation module
const ElementPath = require('elementtree').ElementPath;
// ElementPath module provides the underlying XPath functionality
const find = ElementPath.find;
const findall = ElementPath.findall;
const findtext = ElementPath.findtext;XPath query methods available on both Element and ElementTree instances.
/**
* Find first element matching XPath expression
* @param {string} path - XPath expression
* @returns {Element|null} First matching element or null
*/
find(path): Element | null;
/**
* Find all elements matching XPath expression
* @param {string} path - XPath expression
* @returns {Element[]} Array of matching elements
*/
findall(path): Element[];
/**
* Find text content of first element matching XPath expression
* @param {string} path - XPath expression
* @param {string} defvalue - Default value if no match found
* @returns {string|null} Text content or default value
*/
findtext(path, defvalue): string | null;ElementTree supports the following XPath expressions:
// Select direct child elements by tag name
element.find('child');
element.findall('item');
// Select all direct children
element.findall('*');// Select all descendants with specific tag
element.findall('.//item');
// Select all descendants
element.findall('.//*');// Navigate to parent element
element.find('../..');
element.find('child/..');// Select current element
element.find('.');// Combine path segments
element.find('section/item');
element.findall('category//product');// Select elements with specific attribute
element.findall('item[@id]');
// Select elements with specific attribute value
element.findall('item[@type="book"]');
element.findall('item[@name=\'test\']');// Select elements containing specific child element
element.findall('item[title]');Basic Element Selection:
const et = require('elementtree');
const xml = `
<catalog>
<book id="1">
<title>JavaScript Guide</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book id="2">
<title>Node.js Handbook</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
<magazine id="3">
<title>Tech Weekly</title>
<issue>42</issue>
</magazine>
</catalog>
`;
const catalog = et.XML(xml);
// Find first book
const firstBook = catalog.find('book');
console.log(firstBook.get('id')); // "1"
// Find all books
const allBooks = catalog.findall('book');
console.log(allBooks.length); // 2
// Find book title text
const title = catalog.findtext('book/title');
console.log(title); // "JavaScript Guide"Descendant Selection:
const et = require('elementtree');
const xml = `
<library>
<section name="fiction">
<book><title>Novel 1</title></book>
<book><title>Novel 2</title></book>
</section>
<section name="technical">
<book><title>Tech Book 1</title></book>
<subsection>
<book><title>Advanced Tech</title></book>
</subsection>
</section>
</library>
`;
const library = et.XML(xml);
// Find all books at any level
const allBooks = library.findall('.//book');
console.log(allBooks.length); // 4
// Find all titles at any level
const allTitles = library.findall('.//title');
console.log(allTitles.length); // 4
// Get all title text
allTitles.forEach(title => {
console.log(title.text);
});
// Output: Novel 1, Novel 2, Tech Book 1, Advanced TechAttribute-based Selection:
const et = require('elementtree');
const xml = `
<products>
<item type="book" id="1">JavaScript Guide</item>
<item type="book" id="2">Node.js Handbook</item>
<item type="magazine" id="3">Tech Weekly</item>
<item id="4">No Type</item>
</products>
`;
const products = et.XML(xml);
// Find items with type attribute
const typedItems = products.findall('item[@type]');
console.log(typedItems.length); // 3
// Find only books
const books = products.findall('item[@type="book"]');
console.log(books.length); // 2
// Find specific item by id
const specificItem = products.find('item[@id="3"]');
console.log(specificItem.text); // "Tech Weekly"Parent and Sibling Navigation:
const et = require('elementtree');
const xml = `
<root>
<section>
<item id="1">First</item>
<item id="2">Second</item>
</section>
</root>
`;
const root = et.XML(xml);
// Find item then navigate to parent
const item = root.find('.//item[@id="1"]');
const section = item.find('..');
console.log(section.tag); // "section"
// Navigate to root from deep element
const backToRoot = item.find('../..');
console.log(backToRoot.tag); // "root"Complex Path Expressions:
const et = require('elementtree');
const xml = `
<store>
<category name="electronics">
<product type="laptop">
<name>Gaming Laptop</name>
<specs>
<cpu>Intel i7</cpu>
<ram>16GB</ram>
</specs>
</product>
<product type="phone">
<name>Smartphone</name>
<specs>
<cpu>Snapdragon</cpu>
<ram>8GB</ram>
</specs>
</product>
</category>
</store>
`;
const store = et.XML(xml);
// Find laptops in electronics category
const laptops = store.findall('category[@name="electronics"]/product[@type="laptop"]');
console.log(laptops.length); // 1
// Find all CPU specs at any level
const cpuSpecs = store.findall('.//specs/cpu');
console.log(cpuSpecs[0].text); // "Intel i7"
// Find laptop name
const laptopName = store.findtext('category/product[@type="laptop"]/name');
console.log(laptopName); // "Gaming Laptop"ElementTree supports a subset of XPath. The following are not supported:
/contains(), starts-with())[1], [last()])Invalid XPath expressions will throw SyntaxError:
const et = require('elementtree');
const root = et.Element('root');
try {
// This will throw SyntaxError - absolute paths not supported
root.findall('/root/item');
} catch (error) {
console.error('XPath error:', error.message);
}
try {
// This will throw SyntaxError - malformed predicate
root.findall('item[@id');
} catch (error) {
console.error('XPath error:', error.message);
}XPath expressions can use QName objects for namespaced element selection:
const et = require('elementtree');
// Create QName for namespaced element
const qname = new et.QName('{http://example.com/ns}item');
// Use in XPath (requires proper namespace setup)
const element = et.Element('root');
const result = element.find(qname);