Working with XML in JavaScript (Node.js): Libraries, Parsing and Creation
XML (eXtensible Markup Language) remains a popular format for data exchange in corporate systems, configuration files, and legacy APIs. In the Node.js ecosystem, there are several mature libraries that allow you to efficiently parse, create, and transform XML documents. In this article, we will look at three of the most popular libraries: fast-xml-parser, xml2js and libxmljs, and also show practical examples of their use.
1. fast-xml-parser — fast and secure parser
fast-xml-parser is one of the most performant libraries for working with XML in Node.js. It supports both synchronous and asynchronous parsing, and can also validate XML documents against XSD schemas.
Installation
npm install fast-xml-parserExample of parsing XML into a JavaScript object
const { XMLParser } = require('fast-xml-parser');
const xmlData = `<?xml version="1.0" encoding="UTF-8"?><bookstore> <book category="programming"> <title lang="en">JavaScript: The Good Parts</title> <author>Douglas Crockford</author> <year>2008</year> <price>29.99</price> </book></bookstore>`;
const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_'});
const result = parser.parse(xmlData);console.log(JSON.stringify(result, null, 2));The ignoreAttributes: false setting allows you to preserve XML tag attributes, and attributeNamePrefix adds a prefix to attribute names to prevent conflicts with regular tags.
Creating XML from an object
const { XMLBuilder } = require('fast-xml-parser');
const builder = new XMLBuilder({ format: true, ignoreAttributes: false});
const obj = { bookstore: { book: { '@_category': 'programming', title: { '@_lang': 'en', '#text': 'Clean Code' }, author: 'Robert C. Martin', year: 2008, price: 39.99 } }};
const xmlOutput = builder.build(obj);console.log(xmlOutput);2. xml2js — simple and reliable converter
xml2js is a classic library for converting XML to JSON and back. It provides a simple API and is well documented.
Installation
npm install xml2jsParsing XML with error handling
const xml2js = require('xml2js');const fs = require('fs');
const parser = new xml2js.Parser({ explicitArray: false, // do not wrap single elements in arrays trim: true, normalizeTags: true // normalize tag case});
fs.readFile('config.xml', 'utf-8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } parser.parseString(data, (parseErr, result) => { if (parseErr) { console.error('Error parsing XML:', parseErr); return; } console.log('Configuration parameters:', result.configuration); });});Creating XML with xml2js
const xml2js = require('xml2js');
const builder = new xml2js.Builder({ xmldec: { version: '1.0', encoding: 'UTF-8' }, renderOpts: { pretty: true, indent: ' ' }});
const obj = { response: { status: 'success', data: { user: { id: 123, name: 'Ivan Petrov', email: 'ivan@example.com' } } }};
const xml = builder.buildObject(obj);console.log(xml);3. libxmljs — for advanced XML work
l
Also in library
SignalR for C# (.NET): Complete Guide with Examples
Working with XML in Kotlin: Libraries and Tools for Parsing and Creation
Sending Email in JavaScript (Node.js): Nodemailer, SendGrid, Mailgun
JWT tokens in Rust: libraries and authentication implementation
Data Validation in PHP with the Respect\\Validation Library