xpath.js is a pure JavaScript implementation of the XPath 1.0 specification, designed for use in Node.js environments. Published as version 1.1.0, this library is XML engine agnostic, meaning it requires an external DOM parser (like `xmldom`) to process XML documents. The project's GitHub repository indicates its last commit was approximately five years ago, suggesting it is no longer actively maintained. As such, it primarily supports older Node.js versions and CommonJS modules. Its key differentiator was its pure JavaScript implementation, making it suitable for environments where native XML parsing capabilities were limited, but more modern and actively maintained XPath libraries exist today.
npm install xpath.jsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse an XML string using `xmldom` and then use `xpath.js` to select nodes, extract text content, and retrieve attribute values using XPath 1.0 expressions.
For Node.js environments, use `const select = require('xpath.js');`. If you require ESM, consider using a bundler (like Webpack or Rollup) or evaluate more modern XPath libraries that offer native ESM support.Ensure your XPath expressions conform to the XPath 1.0 specification. For more advanced querying needs, consider alternative, more actively maintained XPath 2.0/3.x libraries or parsing methods.
Assess the risks of using an unmaintained library. For critical applications, consider migrating to an actively maintained XPath library. Regularly review `npm audit` for any reported vulnerabilities, though updates are unlikely.
Always sanitize and validate any user input that is incorporated into XPath expressions. Implement strict input filtering, use parameterized queries if available (not directly supported by this library, so manual sanitization is crucial), and restrict error messages to prevent information disclosure. Consider libraries designed to mitigate injection risks if user input is unavoidable.
Ensure your environment is set up for CommonJS modules, or use a bundler (like Webpack) to transpile the code for ESM. For native Node.js ESM, this package is not directly compatible. Alternatively, change your file extension to `.cjs` if using Node.js modules.
Always check if the result array from `select()` is not empty and contains the expected elements before attempting to access properties like `[0].localName` or `[0].data`. For example: `const nodes = select(doc, '//nonexistent'); if (nodes.length > 0) { console.log(nodes[0].localName); }`Ensure that the XML document is successfully parsed into a DOM structure using a library like `xmldom` before passing it to `xpath.js`. Verify that `new dom().parseFromString(xml, 'text/xml')` returns a valid document object.