Working with XML in JavaScript (Node.js): Parsing, Creation, and Validation

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 Working with XML in Node.js



XML (eXtensible Markup Language) remains a popular format for storing and transmitting structured data, especially in corporate systems, medical protocols, and legacy APIs. 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 the key tools: fast-xml-parser, xml2js, xmlbuilder2, and xpath.



Installing Required Packages



First, install the packages via npm:



npm install fast-xml-parser xml2js xmlbuilder2 xpath


1. Parsing XML with fast-xml-parser



fast-xml-parser is the highest performance library for parsing XML in JavaScript. It supports attributes, namespaces, and conversion to JSON.



Basic Parsing



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

const xmlData = `<bookstore> <book category="fiction"> <title lang="en">The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <year>1925</year> </book></bookstore>`;

const parser = new XMLParser({ ignoreAttributes: false, // Keep attributes attributeNamePrefix: '@_' // Prefix for attributes});

const result = parser.parse(xmlData);console.log(result.bookstore.book[0].title);// 'The Great Gatsby'console.log(result.bookstore.book[0]['@_category']);// 'fiction'


Parsing with Error Checking



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

const invalidXml = '<root><item>Unclosed';

if (XMLValidator.validate(invalidXml) === true) { const parser = new XMLParser(); const data = parser.parse(invalidXml);} else { console.error('Invalid XML'); // Output: true (if valid) or error object}


2. xml2js Library — Convenient Conversion to JSON



xml2js provides a callback-oriented API and supports custom parsing options.



const xml2js = require('xml2js');const parser = new xml2js.Parser({    explicitArray: false, // Do not wrap single elements in an array    attrkey: 'attributes'});

const xml = `<person id="123"> <name>John Doe</name> <age>30</age></person>`;

parser.parseString(xml, (err, result) => { if (err) { console.error('Parsing error:', err); return; } console.log(result.person.name); // 'John Doe' console.log(result.person.attributes.id); // '123'});


Promise Wrapper for xml2js



const { parseStringPromise } = require('xml2js');

async function parseXML(xmlString) { try { const data = await parseStringPromise(xmlString, { explicitArray: false }); return data; } catch (error) { console.error('Error:', error.message); }}


3. Creating XML with xmlbuilder2



xmlbuilder2 is a modern library for generating XML documents with a fluent API.



Simple XML Creation



const { create } = require('xmlbuilder2');

const doc = create({ version: '1.0', encoding: 'UTF-8' }) .ele('catalog') .ele('book', { id: 'b1' }) .ele('title').txt('JavaScript: The Good Parts').up() .ele('author').txt('Douglas Crockford').up() .ele('price', { currency: 'USD' }).txt('29.99').up() .up() .end({ prettyPrint: true });

console.log(doc);


Result:



<?xml version="1.0" encoding="UTF-8"?><catalog>  <book id="b1">    &l                    

Recommendations