Fast XML Parser and Validator
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
-
TypeError: XMLBuilder is not a constructor
cause Attempting to instantiate `XMLBuilder` directly from `fast-xml-parser` after `v5.4.0`.fixInstall `fast-xml-builder` separately (`npm install fast-xml-builder`) and import `XMLBuilder` from its dedicated package: `import XMLBuilder from 'fast-xml-builder';` -
Error: Entity expansion limit crossed.
cause The parsed XML document contains a large number of entities or deeply nested entity expansions, exceeding the default security limits set by the parser.fixInstantiate `XMLParser` with increased entity expansion limits in its options object, for example: `new XMLParser({ maxTotalExpansions: Infinity, maxEntitySize: 50000 });` -
ReferenceError: XMLParser is not defined (when using CommonJS require)
cause Incorrect CommonJS import syntax for named exports. `XMLParser` is a named export.fixFor CommonJS environments, use object destructuring: `const { XMLParser } = require('fast-xml-parser');` -
XML output structure is not as expected (e.g., attributes missing, prefixed, or values not parsed)
cause Default `XMLParser` options (such as `ignoreAttributes`, `attributeNamePrefix`, `parseAttributeValue`) might not align with the desired output structure, leading to unexpected JSON results.fixExplicitly configure the `XMLParser` options during instantiation to control attribute handling, value parsing, and other structural aspects. For example, `new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', parseAttributeValue: true });`
Warnings
- breaking The `XMLBuilder` class was removed from `fast-xml-parser` and moved to a separate package, `fast-xml-builder`. Directly importing or using `XMLBuilder` from `fast-xml-parser` in versions `>=5.4.0` will result in a `TypeError` or `ReferenceError`.
- breaking Version `5.7.1` introduced breaking changes in XML entity processing due to an upgrade of `@nodable/entities`. Specifically, single entity scans prevent entity values from forming other entity names, numeric external entities are no longer allowed, and entity error messages may have changed.
- breaking In `v5.6.0`, when `@nodable/entities` was integrated, error messages for entity-related issues were changed. While not affecting API calls, any code relying on specific error message strings for entities might break.
- gotcha To prevent denial-of-service attacks, `fast-xml-parser` enforces default limits on XML entity expansion (e.g., `maxEntitySize`, `maxExpansionDepth`). Parsing large or complex XML documents with extensive entity use might fail with an 'entity expansion limit crossed' error.
Install
-
npm install fast-xml-parser -
yarn add fast-xml-parser -
pnpm add fast-xml-parser
Imports
- XMLParser
const XMLParser = require('fast-xml-parser');import { XMLParser } from 'fast-xml-parser'; - XMLValidator
import XMLValidator from 'fast-xml-parser';
import { XMLValidator } from 'fast-xml-parser'; - IXMLOptions
import type { IXMLOptions } from 'fast-xml-parser';
Quickstart
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);