0
# xml2js
1
2
xml2js is a bidirectional XML to JavaScript object converter that simplifies XML parsing and building for Node.js applications. It offers multiple parsing approaches including callback-based, promise-based, and stream-based parsing with extensive configuration options for handling attributes, text content, namespaces, and data transformation.
3
4
## Package Information
5
6
- **Package Name**: xml2js
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install xml2js`
10
11
## Core Imports
12
13
```javascript
14
const xml2js = require('xml2js');
15
const { parseString, parseStringPromise, Parser, Builder } = require('xml2js');
16
```
17
18
For ES modules:
19
20
```javascript
21
import xml2js from 'xml2js';
22
import { parseString, parseStringPromise, Parser, Builder } from 'xml2js';
23
```
24
25
## Basic Usage
26
27
```javascript
28
const xml2js = require('xml2js');
29
30
// Simple XML parsing with callback
31
const xmlString = '<root><name>John</name><age>30</age></root>';
32
xml2js.parseString(xmlString, (err, result) => {
33
if (err) throw err;
34
console.log(result); // { root: { name: ['John'], age: ['30'] } }
35
});
36
37
// Promise-based parsing
38
xml2js.parseStringPromise(xmlString)
39
.then(result => console.log(result))
40
.catch(err => console.error(err));
41
42
// Building XML from JavaScript object
43
const builder = new xml2js.Builder();
44
const obj = { root: { name: 'John', age: 30 } };
45
const xml = builder.buildObject(obj);
46
console.log(xml); // <?xml version="1.0" encoding="UTF-8"?>...
47
```
48
49
## Architecture
50
51
xml2js is built around several key components:
52
53
- **SAX Parser Integration**: Uses the SAX parser for efficient, streaming XML parsing
54
- **Configuration System**: Extensive options for customizing parsing and building behavior
55
- **Processing Pipeline**: Built-in text processors for common transformations
56
- **Event-Driven Architecture**: Parser class extends EventEmitter for advanced usage patterns
57
- **xmlbuilder Integration**: Uses xmlbuilder-js for reliable XML generation
58
59
## Capabilities
60
61
### XML Parsing
62
63
Core XML parsing functionality with multiple API approaches for different use cases. Supports callback-based, promise-based, and class-based parsing with extensive configuration.
64
65
```javascript { .api }
66
function parseString(xml: string, callback: (err: Error | null, result?: any) => void): void;
67
function parseString(xml: string, options: ParserOptions, callback: (err: Error | null, result?: any) => void): void;
68
69
function parseStringPromise(xml: string): Promise<any>;
70
function parseStringPromise(xml: string, options: ParserOptions): Promise<any>;
71
72
class Parser extends EventEmitter {
73
constructor(options?: ParserOptions);
74
parseString(xml: string, callback: (err: Error | null, result?: any) => void): void;
75
parseStringPromise(xml: string): Promise<any>;
76
reset(): void;
77
}
78
```
79
80
[XML Parsing](./parsing.md)
81
82
### XML Building
83
84
XML generation functionality for converting JavaScript objects to well-formed XML strings with customizable formatting and structure options.
85
86
```javascript { .api }
87
class Builder {
88
constructor(options?: BuilderOptions);
89
buildObject(rootObj: any): string;
90
}
91
```
92
93
[XML Building](./building.md)
94
95
### Text Processing
96
97
Built-in text processing functions for common XML data transformations including normalization, type conversion, and namespace handling.
98
99
```javascript { .api }
100
const processors: {
101
normalize: (str: string) => string;
102
firstCharLowerCase: (str: string) => string;
103
stripPrefix: (str: string) => string;
104
parseNumbers: (str: string) => string | number;
105
parseBooleans: (str: string) => string | boolean;
106
};
107
```
108
109
[Text Processing](./processing.md)
110
111
### Configuration
112
113
Default configuration presets and validation error handling for different API versions and usage patterns.
114
115
```javascript { .api }
116
const defaults: {
117
"0.1": { explicitArray: boolean; ignoreAttrs: boolean; /* ... */ };
118
"0.2": { explicitArray: boolean; ignoreAttrs: boolean; /* ... */ };
119
};
120
121
class ValidationError extends Error {
122
constructor(message: string);
123
}
124
```
125
126
[Configuration](./configuration.md)
127
128
## Types
129
130
```javascript { .api }
131
interface ParserOptions {
132
attrkey?: string;
133
charkey?: string;
134
explicitCharkey?: boolean;
135
trim?: boolean;
136
normalize?: boolean;
137
normalizeTags?: boolean;
138
explicitRoot?: boolean;
139
explicitArray?: boolean;
140
ignoreAttrs?: boolean;
141
mergeAttrs?: boolean;
142
validator?: (xpath: string, currentValue: any, newValue: any) => any;
143
xmlns?: boolean;
144
explicitChildren?: boolean;
145
childkey?: string;
146
preserveChildrenOrder?: boolean;
147
charsAsChildren?: boolean;
148
includeWhiteChars?: boolean;
149
async?: boolean;
150
strict?: boolean;
151
attrNameProcessors?: Array<(name: string) => string>;
152
attrValueProcessors?: Array<(value: string, name: string) => any>;
153
tagNameProcessors?: Array<(name: string) => string>;
154
valueProcessors?: Array<(value: string, name: string) => any>;
155
emptyTag?: string | (() => string);
156
chunkSize?: number;
157
}
158
159
interface BuilderOptions {
160
attrkey?: string;
161
charkey?: string;
162
rootName?: string;
163
xmldec?: {
164
version?: string;
165
encoding?: string;
166
standalone?: boolean;
167
};
168
doctype?: any;
169
renderOpts?: {
170
pretty?: boolean;
171
indent?: string;
172
newline?: string;
173
};
174
headless?: boolean;
175
allowSurrogateChars?: boolean;
176
cdata?: boolean;
177
}
178
```