Working with XML in JavaScript (Node.js): Libraries and Tools

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to XML Processing in Node.js

XML (eXtensible Markup Language) remains a popular format for storing and transmitting structured data, especially in enterprise systems, SOAP services, configuration files, and integration solutions. In the Node.js ecosystem, there are several mature libraries that allow you to efficiently parse, create, and modify XML documents. In this article, we will look at three main tools: xml2js (for converting XML to JSON and back), fast-xml-parser (a high-performance parser), and xmldom (a DOM Level 2 implementation for Node.js).



1. xml2js Library: Simplicity and Versatility

xml2js is one of the most popular libraries for working with XML in Node.js. Its main task is to convert XML into JavaScript objects (JSON) and back. This is an ideal choice when you need to quickly integrate XML data into a modern JavaScript application.



Installation

npm install xml2js


Example: Parsing XML to JSON

const xml2js = require('xml2js');const parser = new xml2js.Parser({ explicitArray: false });

const xmlData = `<bookstore> <book category="programming"> <title lang="en">Learning Node.js</title> <author>John Doe</author> <price>29.99</price> </book></bookstore>`;

parser.parseString(xmlData, (err, result) => { if (err) { console.error('Parsing error:', err); return; } console.log(JSON.stringify(result, null, 2)); // Output: { bookstore: { book: { category: "programming", title: "Learning Node.js", author: "John Doe", price: "29.99" } } }});


Example: Creating XML from JSON

const xml2js = require('xml2js');const builder = new xml2js.Builder({ headless: true });

const jsonObj = { root: { $: { xmlns: "http://example.com/ns" }, item: [ { $: { id: "1" }, _: "First element" }, { $: { id: "2" }, _: "Second element" } ] }};

const xml = builder.buildObject(jsonObj);console.log(xml);/* Output:<root xmlns="http://example.com/ns"> <item id="1">First element</item> <item id="2">Second element</item></root>*/


Key features:

  • Automatic conversion of attributes (prefix $) and text content (prefix _)
  • Parser configuration: explicitArray, explicitRoot, attrkey, charkey
  • Namespace support
  • Processing large files via streams (streaming parsing)


2. fast-xml-parser: Performance and Flexibility

If you need maximum parsing speed (for example, when processing thousands of XML files or in real-time applications), check out fast-xml-parser. This parser is written in pure JavaScript but is optimized for high performance.



Installation

npm install fast-xml-parser


Example: Fast Parsing with Validation

const { XMLParser, XMLBuilder, XMLValidator } = require('fast-xml-parser');

const xmlData = `<config> <database host="localhost" port="5432"> <user>admin</user> <password>secret</password> </database></config>`;

// Validation checkconst validationResult = XMLValidator.validate(xmlData);if (validationResult !== true) { console.error('XML is invalid:', validationResult.err); process.exit(1);}

// Parsingconst parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "@_"});const jsonObj = parser.parse(xmlData);console.log(jsonObj.config.database["@_host"]); // localhostconsole.log(jsonObj.config.datab

Recommendations