{"id":12690,"library":"xml2js","title":"XML to JavaScript Object Converter","description":"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.","status":"maintenance","version":"0.6.2","language":"javascript","source_language":"en","source_url":"https://github.com/Leonidas-from-XIV/node-xml2js","tags":["javascript","xml","json"],"install":[{"cmd":"npm install xml2js","lang":"bash","label":"npm"},{"cmd":"yarn add xml2js","lang":"bash","label":"yarn"},{"cmd":"pnpm add xml2js","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used internally for parsing XML into a stream of events.","package":"sax-js","optional":false},{"reason":"Used internally for converting JavaScript objects back into XML.","package":"xmlbuilder-js","optional":false}],"imports":[{"note":"For ESM environments, `import { parseString } from 'xml2js';` is correct. The `require` syntax is for CommonJS.","wrong":"const parseString = require('xml2js').parseString;","symbol":"parseString","correct":"import { parseString } from 'xml2js';"},{"note":"While `xml2js` versions 0.2.8+ auto-add `new` for `Parser()`, it's best practice and clearer to explicitly use `new Parser()`.","wrong":"const Parser = require('xml2js').Parser; const parser = Parser();","symbol":"Parser","correct":"import { Parser } from 'xml2js'; const parser = new Parser();"},{"note":"Promise-based parsing method for async/await usage. The `require` form is for CommonJS.","wrong":"const parseStringPromise = require('xml2js').parseStringPromise;","symbol":"parseStringPromise","correct":"import { parseStringPromise } from 'xml2js';"}],"quickstart":{"code":"import { Parser } from 'xml2js';\n\nconst xmlData = `\n<bookstore>\n  <book category=\"COOKING\">\n    <title lang=\"en\">Everyday Italian</title>\n    <author>Giada De Laurentiis</author>\n    <year>2005</year>\n    <price>30.00</price>\n  </book>\n  <book category=\"CHILDREN\">\n    <title lang=\"en\">Harry Potter</title>\n    <author>J.K. Rowling</author>\n    <year>2005</year>\n    <price>29.99</price>\n  </book>\n</bookstore>\n`;\n\nconst parser = new Parser({\n  explicitArray: false, // Ensures single child elements are not arrays\n  mergeAttrs: true,     // Merges attributes into the element object\n  attrkey: 'attributes',// Key for attributes\n  charkey: 'text'       // Key for character data\n});\n\nparser.parseStringPromise(xmlData)\n  .then(result => {\n    console.log('Parsed XML:', JSON.stringify(result, null, 2));\n    const firstBookTitle = result.bookstore.book.title.text;\n    console.log('First book title:', firstBookTitle);\n  })\n  .catch(err => {\n    console.error('Error parsing XML:', err);\n  });\n","lang":"javascript","description":"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."},"warnings":[{"fix":"Always instantiate `Parser` using `new xml2js.Parser()` for clarity and consistency.","message":"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.","severity":"gotcha","affected_versions":"all"},{"fix":"Instantiate `new xml2js.Parser()` for each distinct parsing operation, or call `parser.reset()` if reusing a parser object.","message":"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.","severity":"gotcha","affected_versions":"all"},{"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' }`.","message":"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.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For CommonJS, use `const { parseString } = require('xml2js');` or `const xml2js = require('xml2js'); xml2js.parseString(...);`. For ES Modules, use `import { parseString } from 'xml2js';`.","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.","error":"TypeError: xml2js.parseString is not a function"},{"fix":"Always chain a `.catch(error => { /* handle error */ })` to your `parseStringPromise` calls to gracefully manage parsing failures.","cause":"Using `parseStringPromise` without a `.catch()` handler to deal with potential errors during XML parsing, such as malformed XML or I/O issues.","error":"UnhandledPromiseRejectionWarning: Unhandled promise rejection."}],"ecosystem":"npm"}