Registry / serialization / xml2js

xml2js

JSON →
library0.1jsnpmunverified

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 xml2js
INSTALL
IMPORT
SIG · XML2JS
X
xml2js
serializationjavascriptv0.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

parseString
✓ import { parseString } from 'xml2js';
✗ const parseString = require('xml2js').parseString;
For ESM environments, `import { parseString } from 'xml2js';` is correct. The `require` syntax is for CommonJS.
Parser
✓ import { Parser } from 'xml2js'; const parser = new Parser();
✗ const Parser = require('xml2js').Parser; const parser = Parser();
While `xml2js` versions 0.2.8+ auto-add `new` for `Parser()`, it's best practice and clearer to explicitly use `new Parser()`.
parseStringPromise
✓ import { parseStringPromise } from 'xml2js';
✗ const parseStringPromise = require('xml2js').parseStringPromise;
Promise-based parsing method for async/await usage. The `require` form is for CommonJS.

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.

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); });
Debug
Known issues
gotchaWhen 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.
fix
Always instantiate `Parser` using `new xml2js.Parser()` for clarity and consistency.
affects: all
gotchaFor 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.
fix
Instantiate `new xml2js.Parser()` for each distinct parsing operation, or call `parser.reset()` if reusing a parser object.
affects: all
gotchaThe 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.
fix
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' }`.
affects: all
Errors
Common errors & fixes
TypeError: xml2js.parseString is not a function
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.
fix
For 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.
Using `parseStringPromise` without a `.catch()` handler to deal with potential errors during XML parsing, such as malformed XML or I/O issues.
fix
Always chain a `.catch(error => { /* handle error */ })` to your `parseStringPromise` calls to gracefully manage parsing failures.
Upgrade
Version history
0.1latest on npm
Audit
Dependencies
sax-jsrequiredUsed internally for parsing XML into a stream of events.
xmlbuilder-jsrequiredUsed internally for converting JavaScript objects back into XML.
Agent activity
25 hits · last 30 days
node
22
OpenAI (training)
1
Resources
xml2js — npm install xml2js · libregistry