Working with XML in TypeScript: Libraries for Parsing and Creating XML

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

Working with XML in TypeScript: Library Overview and Practical Examples



XML (eXtensible Markup Language) remains a popular format for data exchange in enterprise systems, configuration files, and web services (SOAP, RSS/Atom). In TypeScript, thanks to static typing, working with XML becomes safer and more predictable. In this article, we will look at three main libraries for working with XML in TypeScript: fast-xml-parser, xml2js, and xmlbuilder2. You will learn how to parse XML, create XML documents, and validate their structure.



1. Installation and Setup



To get started, install one or more libraries via npm:



npm install fast-xml-parser xml2js xmlbuilder2npm install -D @types/xml2js  // types for xml2js (types for fast-xml-parser are built-in)


2. Parsing XML with fast-xml-parser



fast-xml-parser is the fastest library for parsing XML in JavaScript/TypeScript. It supports working with attributes, namespaces, and can convert XML to JSON.



Basic Parsing



import { XMLParser } from 'fast-xml-parser';

const xmlString = `<bookstore> <book category="fiction"> <title>War and Peace</title> <author>Leo Tolstoy</author> <price currency="RUB">1200</price> </book></bookstore>`;

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

const result = parser.parse(xmlString);console.log(result);


The result will be an object:



{  bookstore: {    book: {      '@_category': 'fiction',      title: 'War and Peace',      author: 'Leo Tolstoy',      price: {        '@_currency': 'RUB',        '#text': '1200'      }    }  }}


Parsing with Typing



interface Book {  '@_category': string;  title: string;  author: string;  price: {    '@_currency': string;    '#text': number;  };}

interface Bookstore { bookstore: { book: Book | Book[]; };}

const typedResult = parser.parse(xmlString) as Bookstore;console.log(typedResult.bookstore.book);


3. Parsing XML with xml2js



xml2js is a library with more advanced features, including support for process functions and custom transformations. It works asynchronously.



Asynchronous Parsing



import { parseStringPromise } from 'xml2js';

interface XmlBook { $: { category: string }; title: string[]; author: string[]; price: Array<{ $: { currency: string }, _: string }>;}

async function parseXmlData(xml: string): Promise<void> { try { const result = await parseStringPromise(xml, { explicitArray: false, // do not wrap single elements in arrays attrkey: '$', // key for attributes charkey: '_' // key for text content }); const book = result.bookstore.book as XmlBook; console.log(`Book: ${book.title}, author: ${book.author}`); console.log(`Price: ${book.price._} ${book.price.$.currency}`); } catch (error) { console.error('XML parsing error:', error); }}

parseXmlData(xmlString);


4. Creating XML with xmlbuilder2



xmlbuilder2 is a modern library for creating XML documents with TypeScript support. It provides a chaining API and automatic escaping.



Creating Simple XML



import { create } from 'xmlbuilder2';

const xml = create({ version: '1.0', encoding: 'UTF-8' }) .ele('catalog') .ele('book', { id: '1', category: 'fiction' }) .ele('title').txt('Crime and Punishment').up() .ele('author').tx

Recommendations