Simple XML to JavaScript object converter.
Core XML parsing functionality with multiple API approaches for different use cases. Supports callback-based, promise-based, and class-based parsing with extensive configuration options.
Convenience function for one-off XML parsing with callback-based error handling.
/**
* Parse XML string with callback
* @param xml - XML string to parse
* @param callback - Callback function receiving (err, result)
*/
function parseString(xml: string, callback: (err: Error | null, result?: any) => void): void;
/**
* Parse XML string with options and callback
* @param xml - XML string to parse
* @param options - Parser configuration options
* @param callback - Callback function receiving (err, result)
*/
function parseString(xml: string, options: ParserOptions, callback: (err: Error | null, result?: any) => void): void;Usage Examples:
const xml2js = require('xml2js');
// Basic parsing
const xmlString = '<person><name>Alice</name><age>25</age></person>';
xml2js.parseString(xmlString, (err, result) => {
if (err) {
console.error('Parse error:', err);
return;
}
console.log(result); // { person: { name: ['Alice'], age: ['25'] } }
});
// Parsing with options
const options = {
explicitArray: false,
ignoreAttrs: false,
parseNumbers: true
};
xml2js.parseString(xmlString, options, (err, result) => {
if (err) {
console.error('Parse error:', err);
return;
}
console.log(result); // { person: { name: 'Alice', age: 25 } }
});Promise-based convenience function for modern async/await workflows.
/**
* Parse XML string returning a Promise
* @param xml - XML string to parse
* @returns Promise resolving to parsed result
*/
function parseStringPromise(xml: string): Promise<any>;
/**
* Parse XML string with options returning a Promise
* @param xml - XML string to parse
* @param options - Parser configuration options
* @returns Promise resolving to parsed result
*/
function parseStringPromise(xml: string, options: ParserOptions): Promise<any>;Usage Examples:
const xml2js = require('xml2js');
// Promise-based parsing
async function parseXML() {
try {
const xmlString = '<books><book id="1"><title>Node.js Guide</title></book></books>';
const result = await xml2js.parseStringPromise(xmlString);
console.log(result);
} catch (error) {
console.error('Parse error:', error);
}
}
// With custom options
async function parseWithOptions() {
const options = {
explicitArray: false,
mergeAttrs: true,
trim: true
};
try {
const result = await xml2js.parseStringPromise(xmlString, options);
console.log(result);
} catch (error) {
console.error('Parse error:', error);
}
}Advanced XML parser class with event-driven architecture and reusable instances for multiple parsing operations.
/**
* XML Parser class extending EventEmitter
*/
class Parser extends EventEmitter {
/**
* Create a new Parser instance
* @param options - Parser configuration options
*/
constructor(options?: ParserOptions);
/**
* Parse XML string with callback
* @param xml - XML string to parse
* @param callback - Callback function receiving (err, result)
*/
parseString(xml: string, callback: (err: Error | null, result?: any) => void): void;
/**
* Parse XML string returning a Promise
* @param xml - XML string to parse
* @returns Promise resolving to parsed result
*/
parseStringPromise(xml: string): Promise<any>;
/**
* Reset parser state for reuse
*/
reset(): void;
}Parser Events:
'end' - Emitted when parsing completes successfully with result object'error' - Emitted when parsing fails with error objectUsage Examples:
const xml2js = require('xml2js');
// Create parser instance with options
const parser = new xml2js.Parser({
explicitArray: false,
trim: true,
normalize: true
});
// Event-driven parsing
parser.on('end', (result) => {
console.log('Parsing completed:', result);
});
parser.on('error', (err) => {
console.error('Parsing failed:', err);
});
// Parse multiple documents with same parser
const xml1 = '<doc><title>First Document</title></doc>';
const xml2 = '<doc><title>Second Document</title></doc>';
parser.parseString(xml1, (err, result) => {
if (!err) console.log('First:', result);
});
parser.reset(); // Reset parser state between uses
parser.parseString(xml2, (err, result) => {
if (!err) console.log('Second:', result);
});
// Promise-based usage with parser instance
async function parseMultiple() {
try {
const result1 = await parser.parseStringPromise(xml1);
parser.reset();
const result2 = await parser.parseStringPromise(xml2);
console.log({ result1, result2 });
} catch (error) {
console.error('Parse error:', error);
}
}Static convenience methods on the Parser class for one-off parsing without creating instances.
/**
* Static method for parsing XML with options
* @param xml - XML string to parse
* @param options - Parser configuration options
* @param callback - Callback function receiving (err, result)
*/
static parseString(xml: string, options: ParserOptions, callback: (err: Error | null, result?: any) => void): void;
/**
* Static method for promise-based parsing with options
* @param xml - XML string to parse
* @param options - Parser configuration options
* @returns Promise resolving to parsed result
*/
static parseStringPromise(xml: string, options: ParserOptions): Promise<any>;interface ParserOptions {
/** Prefix for accessing XML attributes (default: '$') */
attrkey?: string;
/** Prefix for accessing character content (default: '_') */
charkey?: string;
/** Always use charkey prefix for character content (default: false) */
explicitCharkey?: boolean;
/** Trim whitespace from text nodes (default: false) */
trim?: boolean;
/** Normalize whitespace in text nodes (default: false) */
normalize?: boolean;
/** Convert tag names to lowercase (default: false) */
normalizeTags?: boolean;
/** Include root element in result (default: true) */
explicitRoot?: boolean;
/** Always use arrays for child elements (default: true) */
explicitArray?: boolean;
/** Ignore XML attributes (default: false) */
ignoreAttrs?: boolean;
/** Merge attributes with child elements (default: false) */
mergeAttrs?: boolean;
/** Value for empty XML elements (default: '') */
emptyTag?: string | (() => string);
}interface AdvancedParserOptions {
/** Custom validation function */
validator?: (xpath: string, currentValue: any, newValue: any) => any;
/** Include namespace information (default: false) */
xmlns?: boolean;
/** Separate child elements property (default: false) */
explicitChildren?: boolean;
/** Prefix for child elements when explicitChildren=true (default: '$$') */
childkey?: string;
/** Maintain child element order (default: false) */
preserveChildrenOrder?: boolean;
/** Treat character data as children (default: false) */
charsAsChildren?: boolean;
/** Include whitespace-only nodes (default: false) */
includeWhiteChars?: boolean;
/** Use async callback execution (default: false) */
async?: boolean;
/** Strict XML parsing mode (default: true) */
strict?: boolean;
/** Chunk size for async processing (default: 10000) */
chunkSize?: number;
}interface ProcessingOptions {
/** Functions to process attribute names */
attrNameProcessors?: Array<(name: string) => string>;
/** Functions to process attribute values */
attrValueProcessors?: Array<(value: string, name: string) => any>;
/** Functions to process tag names */
tagNameProcessors?: Array<(name: string) => string>;
/** Functions to process element values */
valueProcessors?: Array<(value: string, name: string) => any>;
}Usage Examples:
const xml2js = require('xml2js');
// Complex configuration example
const options = {
// Customize keys
attrkey: 'attributes',
charkey: 'content',
explicitCharkey: true,
// Text processing
trim: true,
normalize: true,
normalizeTags: true,
// Structure options
explicitRoot: false,
explicitArray: false,
mergeAttrs: true,
// Processing functions
tagNameProcessors: [xml2js.processors.firstCharLowerCase],
valueProcessors: [xml2js.processors.parseNumbers, xml2js.processors.parseBooleans],
attrValueProcessors: [xml2js.processors.parseNumbers]
};
const xmlString = `
<Product ID="123" Active="true">
<Name>Laptop Computer</Name>
<Price>999.99</Price>
<InStock>5</InStock>
</Product>
`;
xml2js.parseString(xmlString, options, (err, result) => {
if (!err) {
console.log(result);
// Result will have processed tag names, parsed numbers/booleans
}
});Install with Tessl CLI
npx tessl i tessl/npm-xml2js