XML to JavaScript Object Converter
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.
Common errors
-
TypeError: xml2js.parseString is not a function
cause Attempting to use named exports (`parseString`, `parseStringPromise`) directly from a CommonJS `require` statement as if it were an ES module default export, or a CommonJS module with a `default` export.fixFor CommonJS, use `const { parseString } = require('xml2js');` or `const xml2js = require('xml2js'); xml2js.parseString(...);`. For ES Modules, use `import { parseString } from 'xml2js';`. -
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
cause Using `parseStringPromise` without a `.catch()` handler to deal with potential errors during XML parsing, such as malformed XML or I/O issues.fixAlways chain a `.catch(error => { /* handle error */ })` to your `parseStringPromise` calls to gracefully manage parsing failures.
Warnings
- gotcha When creating a new `Parser` instance, explicitly using the `new` keyword (e.g., `new Parser()`) is best practice, even though versions 0.2.8 and above will automatically add it if omitted. Relying on this auto-correction can lead to less readable code and potential confusion in older environments or with stricter linters.
- gotcha For parsing multiple XML files or strings, it is strongly recommended to create a new `xml2js.Parser` instance for each operation. Reusing a single parser instance across multiple parsing tasks without calling `reset()` is not guaranteed to work correctly and can lead to unexpected behavior or corrupted results.
- gotcha The default parsing behavior of `xml2js` can sometimes result in verbose or unexpected object structures (e.g., single child elements being wrapped in arrays, attributes nested under an 'attr' key). This often requires configuring options like `explicitArray`, `mergeAttrs`, `attrkey`, and `charkey` to achieve a more consumable JavaScript object structure.
Install
-
npm install xml2js -
yarn add xml2js -
pnpm add xml2js
Imports
- parseString
const parseString = require('xml2js').parseString;import { parseString } from 'xml2js'; - Parser
const Parser = require('xml2js').Parser; const parser = Parser();import { Parser } from 'xml2js'; const parser = new Parser(); - parseStringPromise
const parseStringPromise = require('xml2js').parseStringPromise;import { parseStringPromise } from 'xml2js';
Quickstart
import { Parser } from 'xml2js';
const xmlData = `
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
`;
const parser = new Parser({
explicitArray: false, // Ensures single child elements are not arrays
mergeAttrs: true, // Merges attributes into the element object
attrkey: 'attributes',// Key for attributes
charkey: 'text' // Key for character data
});
parser.parseStringPromise(xmlData)
.then(result => {
console.log('Parsed XML:', JSON.stringify(result, null, 2));
const firstBookTitle = result.bookstore.book.title.text;
console.log('First book title:', firstBookTitle);
})
.catch(err => {
console.error('Error parsing XML:', err);
});