XML-JS Converter

1.6.11 · active · verified Sun Apr 19

xml-js is a robust JavaScript library designed for converting between XML text and JavaScript objects or JSON text. It is currently stable at version 1.6.11 and receives active maintenance, with recent updates focusing on performance optimizations and new features like custom processing functions. A key differentiator is its ability to maintain the original order of XML elements during conversion to a JavaScript object, avoiding the common practice of merging same-named nodes into arrays by default, which is crucial for preserving document structure. It supports full XML compliance, parsing elements, attributes, texts, comments, CData, DOCTYPEs, XML declarations, and Processing Instructions. The library is also reversible, meaning conversions from XML to JS/JSON and back to XML will preserve the original data. It is known for its minimal dependencies and portability, working in both Node.js and browser environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting an XML string to JavaScript objects in both compact and non-compact modes, then converting these JavaScript objects back into formatted XML strings.

import { xml2js, js2xml } from 'xml-js';

// Example XML string
const xmlString = `
  <?xml version="1.0" encoding="UTF-8"?>
  <!-- Sample XML Document -->
  <bookstore>
    <book category="programming">
      <title lang="en">Learning XML</title>
      <author>John Doe</author>
      <price>39.95</price>
    </book>
    <book category="web">
      <title lang="en">HTML &amp; CSS</title>
      <author>Jane Smith</author>
      <price>29.99</price>
      <description><![CDATA[A comprehensive guide to web design.]]></description>
    </book>
  </bookstore>
`;

// 1. Convert XML to JavaScript object (non-compact, preserving order)
const jsObjectNonCompact = xml2js(xmlString, { compact: false, spaces: 2 });
console.log('--- Non-Compact JS Object ---');
console.log(JSON.stringify(jsObjectNonCompact, null, 2));

// 2. Convert XML to JavaScript object (compact mode)
const jsObjectCompact = xml2js(xmlString, { compact: true, spaces: 2 });
console.log('\n--- Compact JS Object ---');
console.log(JSON.stringify(jsObjectCompact, null, 2));

// 3. Convert JavaScript object back to XML (from compact object)
const xmlOutputFromCompact = js2xml(jsObjectCompact, { compact: true, spaces: 2 });
console.log('\n--- XML Output from Compact JS Object ---');
console.log(xmlOutputFromCompact);

// 4. Convert JavaScript object back to XML (from non-compact object)
const xmlOutputFromNonCompact = js2xml(jsObjectNonCompact, { compact: false, spaces: 2 });
console.log('\n--- XML Output from Non-Compact JS Object ---');
console.log(xmlOutputFromNonCompact);

view raw JSON →