or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

building.mdindex.mdparsing.mdvalidation.md
tile.json

parsing.mddocs/

XML Parsing

Comprehensive XML to JavaScript object conversion with extensive configuration options for handling attributes, namespaces, entities, data types, and structural transformations.

Capabilities

XMLParser Class

Main parser class that converts XML strings or Buffers into JavaScript objects with customizable parsing behavior.

/**
 * Creates a new XMLParser instance with optional configuration
 * @param options - Parser configuration options
 */
class XMLParser {
  constructor(options?: X2jOptions);
}

parse Method

Parses XML data into JavaScript objects with optional validation.

/**
 * Parses XML data into JavaScript objects
 * @param xmlData - XML content as string or Buffer
 * @param validationOptions - Optional validation settings or boolean to enable default validation
 * @returns Parsed JavaScript object representation of the XML
 */
parse(xmlData: string | Buffer, validationOptions?: validationOptions | boolean): any;

Usage Examples:

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

// Basic parsing
const parser = new XMLParser();
const result = parser.parse('<root><item>value</item></root>');
console.log(result); // { root: { item: "value" } }

// With validation
const xmlString = '<root><item>value</item></root>';
const validatedResult = parser.parse(xmlString, true);

// With custom validation options
const customResult = parser.parse(xmlString, {
  allowBooleanAttributes: true,
  unpairedTags: ['br', 'hr']
});

addEntity Method

Adds custom XML entity support beyond the built-in entities.

/**
 * Add Entity which is not by default supported by this library
 * @param entityIdentifier - Entity name (e.g., 'ent' for &ent;)
 * @param entityValue - Entity replacement value (e.g., '\r')
 */
addEntity(entityIdentifier: string, entityValue: string): void;

Usage Example:

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

const parser = new XMLParser();

// Add custom entity
parser.addEntity('customEntity', 'Custom Value');

// Now &customEntity; will be replaced with 'Custom Value'
const result = parser.parse('<root>&customEntity;</root>');

getMetaDataSymbol Method

Returns the Symbol used to access metadata properties on parsed nodes when metadata capture is enabled.

/**
 * Returns a Symbol that can be used to access the XMLMetaData property on a node
 * If Symbol is not available, returns an ordinary property name
 * Only relevant when X2jOptions.captureMetaData is true
 */
static getMetaDataSymbol(): Symbol;

Usage Example:

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

const parser = new XMLParser({ captureMetaData: true });
const result = parser.parse('<root>content</root>');

const metaSymbol = XMLParser.getMetaDataSymbol();
const metadata = result.root[metaSymbol];
console.log(metadata.startIndex); // Character position where <root> began

Configuration Options

X2jOptions Interface

Comprehensive configuration interface for XMLParser with extensive customization options.

interface X2jOptions {
  /** Preserve the order of tags in resulting JS object */
  preserveOrder?: boolean;
  
  /** Give a prefix to the attribute name in the resulting JS object */
  attributeNamePrefix?: string;
  
  /** A name to group all attributes of a tag under, or false to disable */
  attributesGroupName?: false | string;
  
  /** The name of the text node in the resulting JS */
  textNodeName?: string;
  
  /** Whether to ignore attributes when parsing */
  ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean);
  
  /** Whether to remove namespace string from tag and attribute names */
  removeNSPrefix?: boolean;
  
  /** Whether to allow attributes without value */
  allowBooleanAttributes?: boolean;
  
  /** Whether to parse tag value with strnum package */
  parseTagValue?: boolean;
  
  /** Whether to parse attribute values with strnum package */
  parseAttributeValue?: boolean;
  
  /** Whether to remove surrounding whitespace from tag or attribute value */
  trimValues?: boolean;
  
  /** Give a property name to set CDATA values to instead of merging to tag's text value */
  cdataPropName?: false | string;
  
  /** If set, parse comments and set as this property */
  commentPropName?: false | string;
  
  /** Control how tag value should be parsed */
  tagValueProcessor?: (tagName: string, tagValue: string, jPath: string, hasAttributes: boolean, isLeafNode: boolean) => unknown;
  
  /** Control how attribute value should be parsed */
  attributeValueProcessor?: (attrName: string, attrValue: string, jPath: string) => unknown;
  
  /** Options to pass to strnum for parsing numbers */
  numberParseOptions?: strnumOptions;
  
  /** Nodes to stop parsing at */
  stopNodes?: string[];
  
  /** List of tags without closing tags */
  unpairedTags?: string[];
  
  /** Whether to always create a text node */
  alwaysCreateTextNode?: boolean;
  
  /** Determine whether a tag should be parsed as an array */
  isArray?: (tagName: string, jPath: string, isLeafNode: boolean, isAttribute: boolean) => boolean;
  
  /** Whether to process default and DOCTYPE entities */
  processEntities?: boolean;
  
  /** Whether to process HTML entities */
  htmlEntities?: boolean;
  
  /** Whether to ignore the declaration tag from output */
  ignoreDeclaration?: boolean;
  
  /** Whether to ignore PI tags */
  ignorePiTags?: boolean;
  
  /** Transform tag names */
  transformTagName?: ((tagName: string) => string) | false;
  
  /** Transform attribute names */
  transformAttributeName?: ((attributeName: string) => string) | false;
  
  /** Change the tag name when a different name is returned. Skip the tag from parsed result when false is returned. */
  updateTag?: (tagName: string, jPath: string, attrs: {[k: string]: string}) => string | boolean;
  
  /** If true, adds a Symbol to all object nodes with metadata about each node in the XML file */
  captureMetaData?: boolean;
}

Supporting Types

Additional interfaces used by the parser configuration.

interface strnumOptions {
  hex: boolean;
  leadingZeros: boolean;
  skipLike?: RegExp;
  eNotation?: boolean;
}

interface XMLMetaData {
  /** The index, if available, of the character where the XML node began in the input stream */
  startIndex?: number;
}

Common Parsing Scenarios

Attribute Handling

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

// Default: attributes ignored
const parser1 = new XMLParser();
const result1 = parser1.parse('<item id="123">value</item>');
// Result: { item: "value" }

// Parse attributes with prefix
const parser2 = new XMLParser({ 
  ignoreAttributes: false,
  attributeNamePrefix: "@_"
});
const result2 = parser2.parse('<item id="123">value</item>');
// Result: { item: { "@_id": "123", "#text": "value" } }

// Group attributes
const parser3 = new XMLParser({ 
  ignoreAttributes: false,
  attributesGroupName: "@"
});
const result3 = parser3.parse('<item id="123" name="test">value</item>');
// Result: { item: { "@": { id: "123", name: "test" }, "#text": "value" } }

Value Processing

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

// Parse numeric values
const parser = new XMLParser({ 
  parseTagValue: true,
  parseAttributeValue: true 
});
const result = parser.parse('<item count="5">123.45</item>');
// Result: { item: { "@_count": 5, "#text": 123.45 } }

// Custom value processing
const customParser = new XMLParser({
  tagValueProcessor: (tagName, tagValue) => {
    if (tagName === 'price') return parseFloat(tagValue);
    return tagValue;
  }
});

Array Detection

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

const parser = new XMLParser({
  isArray: (tagName, jPath, isLeafNode, isAttribute) => {
    return tagName === 'item';
  }
});

const xml = '<root><item>1</item><item>2</item></root>';
const result = parser.parse(xml);
// Result: { root: { item: ["1", "2"] } }

Entity Processing

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

// Enable HTML entities
const parser = new XMLParser({ 
  processEntities: true,
  htmlEntities: true 
});

const result = parser.parse('<text>&lt;hello&gt; &amp; &nbsp;</text>');
// Entities are decoded automatically

// Add custom entities
parser.addEntity('copy', '©');
const customResult = parser.parse('<text>&copy; 2023</text>');

Namespace Handling

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

// Remove namespace prefixes
const parser = new XMLParser({ 
  removeNSPrefix: true,
  ignoreAttributes: false 
});

const xml = '<ns:root xmlns:ns="http://example.com"><ns:item>value</ns:item></ns:root>';
const result = parser.parse(xml);
// Namespace prefixes are removed from tag names

Performance Optimization

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

// Skip heavy processing for certain nodes
const parser = new XMLParser({
  stopNodes: ['script', 'style'],  // Don't parse these tags
  ignoreAttributes: true,          // Skip attributes if not needed
  parseTagValue: false            // Skip number parsing for speed
});