0
# XML Parsing
1
2
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.
3
4
## Capabilities
5
6
### parseString Function
7
8
Convenience function for one-off XML parsing with callback-based error handling.
9
10
```javascript { .api }
11
/**
12
* Parse XML string with callback
13
* @param xml - XML string to parse
14
* @param callback - Callback function receiving (err, result)
15
*/
16
function parseString(xml: string, callback: (err: Error | null, result?: any) => void): void;
17
18
/**
19
* Parse XML string with options and callback
20
* @param xml - XML string to parse
21
* @param options - Parser configuration options
22
* @param callback - Callback function receiving (err, result)
23
*/
24
function parseString(xml: string, options: ParserOptions, callback: (err: Error | null, result?: any) => void): void;
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
const xml2js = require('xml2js');
31
32
// Basic parsing
33
const xmlString = '<person><name>Alice</name><age>25</age></person>';
34
xml2js.parseString(xmlString, (err, result) => {
35
if (err) {
36
console.error('Parse error:', err);
37
return;
38
}
39
console.log(result); // { person: { name: ['Alice'], age: ['25'] } }
40
});
41
42
// Parsing with options
43
const options = {
44
explicitArray: false,
45
ignoreAttrs: false,
46
parseNumbers: true
47
};
48
xml2js.parseString(xmlString, options, (err, result) => {
49
if (err) {
50
console.error('Parse error:', err);
51
return;
52
}
53
console.log(result); // { person: { name: 'Alice', age: 25 } }
54
});
55
```
56
57
### parseStringPromise Function
58
59
Promise-based convenience function for modern async/await workflows.
60
61
```javascript { .api }
62
/**
63
* Parse XML string returning a Promise
64
* @param xml - XML string to parse
65
* @returns Promise resolving to parsed result
66
*/
67
function parseStringPromise(xml: string): Promise<any>;
68
69
/**
70
* Parse XML string with options returning a Promise
71
* @param xml - XML string to parse
72
* @param options - Parser configuration options
73
* @returns Promise resolving to parsed result
74
*/
75
function parseStringPromise(xml: string, options: ParserOptions): Promise<any>;
76
```
77
78
**Usage Examples:**
79
80
```javascript
81
const xml2js = require('xml2js');
82
83
// Promise-based parsing
84
async function parseXML() {
85
try {
86
const xmlString = '<books><book id="1"><title>Node.js Guide</title></book></books>';
87
const result = await xml2js.parseStringPromise(xmlString);
88
console.log(result);
89
} catch (error) {
90
console.error('Parse error:', error);
91
}
92
}
93
94
// With custom options
95
async function parseWithOptions() {
96
const options = {
97
explicitArray: false,
98
mergeAttrs: true,
99
trim: true
100
};
101
102
try {
103
const result = await xml2js.parseStringPromise(xmlString, options);
104
console.log(result);
105
} catch (error) {
106
console.error('Parse error:', error);
107
}
108
}
109
```
110
111
### Parser Class
112
113
Advanced XML parser class with event-driven architecture and reusable instances for multiple parsing operations.
114
115
```javascript { .api }
116
/**
117
* XML Parser class extending EventEmitter
118
*/
119
class Parser extends EventEmitter {
120
/**
121
* Create a new Parser instance
122
* @param options - Parser configuration options
123
*/
124
constructor(options?: ParserOptions);
125
126
/**
127
* Parse XML string with callback
128
* @param xml - XML string to parse
129
* @param callback - Callback function receiving (err, result)
130
*/
131
parseString(xml: string, callback: (err: Error | null, result?: any) => void): void;
132
133
/**
134
* Parse XML string returning a Promise
135
* @param xml - XML string to parse
136
* @returns Promise resolving to parsed result
137
*/
138
parseStringPromise(xml: string): Promise<any>;
139
140
/**
141
* Reset parser state for reuse
142
*/
143
reset(): void;
144
}
145
```
146
147
**Parser Events:**
148
149
- `'end'` - Emitted when parsing completes successfully with result object
150
- `'error'` - Emitted when parsing fails with error object
151
152
**Usage Examples:**
153
154
```javascript
155
const xml2js = require('xml2js');
156
157
// Create parser instance with options
158
const parser = new xml2js.Parser({
159
explicitArray: false,
160
trim: true,
161
normalize: true
162
});
163
164
// Event-driven parsing
165
parser.on('end', (result) => {
166
console.log('Parsing completed:', result);
167
});
168
169
parser.on('error', (err) => {
170
console.error('Parsing failed:', err);
171
});
172
173
// Parse multiple documents with same parser
174
const xml1 = '<doc><title>First Document</title></doc>';
175
const xml2 = '<doc><title>Second Document</title></doc>';
176
177
parser.parseString(xml1, (err, result) => {
178
if (!err) console.log('First:', result);
179
});
180
181
parser.reset(); // Reset parser state between uses
182
183
parser.parseString(xml2, (err, result) => {
184
if (!err) console.log('Second:', result);
185
});
186
187
// Promise-based usage with parser instance
188
async function parseMultiple() {
189
try {
190
const result1 = await parser.parseStringPromise(xml1);
191
parser.reset();
192
const result2 = await parser.parseStringPromise(xml2);
193
console.log({ result1, result2 });
194
} catch (error) {
195
console.error('Parse error:', error);
196
}
197
}
198
```
199
200
### Static Parser Methods
201
202
Static convenience methods on the Parser class for one-off parsing without creating instances.
203
204
```javascript { .api }
205
/**
206
* Static method for parsing XML with options
207
* @param xml - XML string to parse
208
* @param options - Parser configuration options
209
* @param callback - Callback function receiving (err, result)
210
*/
211
static parseString(xml: string, options: ParserOptions, callback: (err: Error | null, result?: any) => void): void;
212
213
/**
214
* Static method for promise-based parsing with options
215
* @param xml - XML string to parse
216
* @param options - Parser configuration options
217
* @returns Promise resolving to parsed result
218
*/
219
static parseStringPromise(xml: string, options: ParserOptions): Promise<any>;
220
```
221
222
## Parser Configuration Options
223
224
### Core Parsing Options
225
226
```javascript { .api }
227
interface ParserOptions {
228
/** Prefix for accessing XML attributes (default: '$') */
229
attrkey?: string;
230
231
/** Prefix for accessing character content (default: '_') */
232
charkey?: string;
233
234
/** Always use charkey prefix for character content (default: false) */
235
explicitCharkey?: boolean;
236
237
/** Trim whitespace from text nodes (default: false) */
238
trim?: boolean;
239
240
/** Normalize whitespace in text nodes (default: false) */
241
normalize?: boolean;
242
243
/** Convert tag names to lowercase (default: false) */
244
normalizeTags?: boolean;
245
246
/** Include root element in result (default: true) */
247
explicitRoot?: boolean;
248
249
/** Always use arrays for child elements (default: true) */
250
explicitArray?: boolean;
251
252
/** Ignore XML attributes (default: false) */
253
ignoreAttrs?: boolean;
254
255
/** Merge attributes with child elements (default: false) */
256
mergeAttrs?: boolean;
257
258
/** Value for empty XML elements (default: '') */
259
emptyTag?: string | (() => string);
260
}
261
```
262
263
### Advanced Parsing Options
264
265
```javascript { .api }
266
interface AdvancedParserOptions {
267
/** Custom validation function */
268
validator?: (xpath: string, currentValue: any, newValue: any) => any;
269
270
/** Include namespace information (default: false) */
271
xmlns?: boolean;
272
273
/** Separate child elements property (default: false) */
274
explicitChildren?: boolean;
275
276
/** Prefix for child elements when explicitChildren=true (default: '$$') */
277
childkey?: string;
278
279
/** Maintain child element order (default: false) */
280
preserveChildrenOrder?: boolean;
281
282
/** Treat character data as children (default: false) */
283
charsAsChildren?: boolean;
284
285
/** Include whitespace-only nodes (default: false) */
286
includeWhiteChars?: boolean;
287
288
/** Use async callback execution (default: false) */
289
async?: boolean;
290
291
/** Strict XML parsing mode (default: true) */
292
strict?: boolean;
293
294
/** Chunk size for async processing (default: 10000) */
295
chunkSize?: number;
296
}
297
```
298
299
### Processing Options
300
301
```javascript { .api }
302
interface ProcessingOptions {
303
/** Functions to process attribute names */
304
attrNameProcessors?: Array<(name: string) => string>;
305
306
/** Functions to process attribute values */
307
attrValueProcessors?: Array<(value: string, name: string) => any>;
308
309
/** Functions to process tag names */
310
tagNameProcessors?: Array<(name: string) => string>;
311
312
/** Functions to process element values */
313
valueProcessors?: Array<(value: string, name: string) => any>;
314
}
315
```
316
317
**Usage Examples:**
318
319
```javascript
320
const xml2js = require('xml2js');
321
322
// Complex configuration example
323
const options = {
324
// Customize keys
325
attrkey: 'attributes',
326
charkey: 'content',
327
explicitCharkey: true,
328
329
// Text processing
330
trim: true,
331
normalize: true,
332
normalizeTags: true,
333
334
// Structure options
335
explicitRoot: false,
336
explicitArray: false,
337
mergeAttrs: true,
338
339
// Processing functions
340
tagNameProcessors: [xml2js.processors.firstCharLowerCase],
341
valueProcessors: [xml2js.processors.parseNumbers, xml2js.processors.parseBooleans],
342
attrValueProcessors: [xml2js.processors.parseNumbers]
343
};
344
345
const xmlString = `
346
<Product ID="123" Active="true">
347
<Name>Laptop Computer</Name>
348
<Price>999.99</Price>
349
<InStock>5</InStock>
350
</Product>
351
`;
352
353
xml2js.parseString(xmlString, options, (err, result) => {
354
if (!err) {
355
console.log(result);
356
// Result will have processed tag names, parsed numbers/booleans
357
}
358
});
359
```