Working with XML in TypeScript: Libraries and Practical Examples
XML (eXtensible Markup Language) remains a popular format for data exchange, configuration files, and integration with legacy systems. Despite the popularity of JSON, many enterprise solutions, SOAP services, and data formats (e.g., SVG, RSS, XSLT) still use XML. In TypeScript, thanks to static typing, working with XML becomes more reliable and predictable. In this article, we will cover the best libraries for parsing, creating, and validating XML documents in TypeScript.
Main Libraries for Working with XML in TypeScript
Today, there are several mature libraries that work well with TypeScript. Let's look at the three most popular ones:
- fast-xml-parser — the fastest library for parsing XML in JavaScript/TypeScript. Supports validation, conversion to JSON and back.
- xml2js — a classic library with a simple API, converts XML to JavaScript objects. Has built-in TypeScript support via @types/xml2js.
- xmldom — a DOM Level 2 implementation for Node.js, allows working with XML as a DOM tree (similar to the browser's DOMParser).
Installation and Setup
To get started, install one of the libraries via npm:
npm install fast-xml-parser xml2js xmldom @types/xml2jsNow let's look at practical examples for each library.
Example 1: Parsing XML with fast-xml-parser
fast-xml-parser offers high performance and a convenient API for converting XML into plain TypeScript objects.
import { XMLParser, XMLBuilder, XMLValidator } from 'fast-xml-parser';
// Source XMLconst xmlData = `<?xml version="1.0" encoding="UTF-8"?><catalog> <book id="101"> <title>TypeScript Handbook</title> <author>Microsoft</author> <price currency="USD">29.99</price> </book> <book id="102"> <title>Node.js Design Patterns</title> <author>Mario Casciaro</author> <price currency="EUR">34.50</price> </book></catalog>`;
// Parser optionsconst parser = new XMLParser({ ignoreAttributes: false, // Keep attributes attributeNamePrefix: '@_', // Prefix for attributes textNodeName: '#text', // Name for text nodes isArray: (tagName) => ['book'].includes(tagName) // Always return an array for <book>});
// Parsingconst result = parser.parse(xmlData);console.log(JSON.stringify(result, null, 2));
// Typing the resultinterface Book { '@_id': string; title: string; author: string; price: { '@_currency': string; '#text': string; };}
interface Catalog { catalog: { book: Book[]; };}
const catalog = result as Catalog;console.log(`First book: ${catalog.catalog.book[0].title}`);Note the isArray parameter — it ensures that the book element will always be an array, even if only one book is encountered in the XML.
Example 2: Creating XML with xml2js
The xml2js library is convenient for building XML from JavaScript objects. It uses Builder for serialization.
import { Builder } from 'xml2js';
// Object to convert to XMLconst data = { root: { $: { version: '1.0', encoding: 'UTF-8' }, user: [ { $: { id: '1', active: 'true' }, name: 'Ivan Petrov', email: 'ivan@example.com', roles: { role: ['admin', 'editor'] } }, { $: { id: '2', active: 'false' }, name: 'Maria Sidorova', email: 'maria@example.com', roles: { role: ['viewer']