Fast XML Parser and Validator

5.7.1 · active · verified Tue Apr 21

fast-xml-parser is a robust JavaScript library for parsing XML to JavaScript objects, validating XML syntactically, and historically, building XML from JS objects. It is engineered for speed and efficiency, capable of handling large XML files (tested up to 100MB) without relying on C/C++ native libraries. As of v5.7.1, the package is actively maintained with frequent minor and patch releases, incorporating performance improvements and dependency updates. A key differentiator is its pure JavaScript implementation, broad compatibility (CommonJS, ESM, and browser environments), and extensive support for various XML features including entities, unpaired tags, and customizable parsing options. The XML Builder functionality was separated into a dedicated `fast-xml-builder` package in version v5.4.0, focusing `fast-xml-parser` primarily on parsing and validation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to validate an XML string and then parse it into a JavaScript object using common configuration options, and how to access the parsed data.

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

const xmlData = `<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J.K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
</bookstore>`;

// 1. Validate XML
const validationResult = XMLValidator.validate(xmlData);
if (validationResult === true) {
  console.log('XML is syntactically valid.');
} else {
  console.error('XML validation failed:', validationResult);
  // In a real application, you might throw or exit here.
}

// 2. Parse XML to a JavaScript object
const parserOptions = {
  ignoreAttributes: false, // Keep attributes
  attributeNamePrefix: "@_", // Prefix for attributes
  allowBooleanAttributes: true, // Handle boolean attributes like <tag checked/>
  parseTagValue: true, // Attempt to parse values as numbers/booleans
  parseAttributeValue: true, // Attempt to parse attribute values
  trimValues: true, // Trim whitespace from values
  cdataPropName: "cdata" // Name for CDATA section property
};
const parser = new XMLParser(parserOptions);

const jsonObj = parser.parse(xmlData);
console.log('Parsed JSON object:\n', JSON.stringify(jsonObj, null, 2));

// Example of accessing parsed data
console.log('\nFirst book title:', jsonObj.bookstore.book[0].title['#text']);
console.log('Second book author:', jsonObj.bookstore.book[1].author);

view raw JSON →