XML to JavaScript Object Converter

0.6.2 · maintenance · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

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);
  });

view raw JSON →