xml2js is a JavaScript library designed for converting XML data into JavaScript objects and vice-versa. It provides a straightforward API for parsing XML strings or streams, abstracting away the complexities of low-level XML parsing. The current stable version provided is 0.6.2. The library differentiates itself by focusing on simplicity and ease of use, leveraging `sax-js` for robust parsing and `xmlbuilder-js` for object-to-XML conversion. It offers both callback-based and Promise-based parsing methods, catering to different asynchronous programming styles. While not a full DOM parser like JSDom, it excels at transforming structured XML into a consumable JavaScript object hierarchy, making it suitable for data interchange and configuration file processing. Release cadence appears stable but not rapid, typical for a mature utility library.
npm install xml2jsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates parsing a multi-element XML string into a JavaScript object using `parseStringPromise` with common options for cleaner output, then accessing specific data points.
Always instantiate `Parser` using `new xml2js.Parser()` for clarity and consistency.
Instantiate `new xml2js.Parser()` for each distinct parsing operation, or call `parser.reset()` if reusing a parser object.
Thoroughly review the available `Parser` options and apply them to tailor the output object structure to your needs. Common options include `{ explicitArray: false, mergeAttrs: true, attrkey: '$', charkey: '_value' }`.For CommonJS, use `const { parseString } = require('xml2js');` or `const xml2js = require('xml2js'); xml2js.parseString(...);`. For ES Modules, use `import { parseString } from 'xml2js';`.Always chain a `.catch(error => { /* handle error */ })` to your `parseStringPromise` calls to gracefully manage parsing failures.