0
# xml2json
1
2
xml2json is a JavaScript library for converting between XML and JSON formats. It uses the node-expat parser for fast and reliable XML processing, supporting bidirectional conversion with comprehensive configuration options for both directions.
3
4
## Package Information
5
6
- **Package Name**: xml2json
7
- **Package Type**: npm
8
- **Language**: JavaScript (Node.js)
9
- **Installation**: `npm install xml2json`
10
11
## Core Imports
12
13
```javascript
14
const parser = require('xml2json');
15
```
16
17
For ES modules:
18
```javascript
19
import parser from 'xml2json';
20
```
21
22
## Basic Usage
23
24
```javascript
25
const parser = require('xml2json');
26
27
// XML to JSON conversion
28
const xml = '<person name="John" age="30"><city>New York</city></person>';
29
const json = parser.toJson(xml);
30
console.log(json);
31
// Output: {"person":{"name":"John","age":"30","city":"New York"}}
32
33
// JSON to XML conversion
34
const xmlBack = parser.toXml(json);
35
console.log(xmlBack);
36
// Output: <person name="John" age="30"><city>New York</city></person>
37
38
// Return JavaScript object instead of JSON string
39
const obj = parser.toJson(xml, { object: true });
40
console.log(obj.person.name); // "John"
41
console.log(obj.person.city); // "New York"
42
```
43
44
## Capabilities
45
46
### XML to JSON Conversion
47
48
Converts XML strings or buffers to JSON format with extensive configuration options.
49
50
```javascript { .api }
51
/**
52
* Converts XML to JSON string or JavaScript object
53
* @param {String|Buffer} xml - XML string or buffer to convert
54
* @param {Object} options - Configuration options for conversion
55
* @returns {String|Object} JSON string or JavaScript object
56
*/
57
function toJson(xml, options);
58
```
59
60
**Parameters:**
61
- `xml` (String|Buffer): XML content to convert
62
- `options` (Object, optional): Configuration options
63
64
**Returns:** String (JSON) or Object (if `options.object` is true)
65
66
**Usage Examples:**
67
68
```javascript
69
// Basic conversion
70
const json = parser.toJson('<root><item>value</item></root>');
71
72
// Return JavaScript object
73
const obj = parser.toJson(xml, { object: true });
74
75
// Enable type coercion for numbers and booleans
76
const typed = parser.toJson('<data><count>42</count><active>true</active></data>', {
77
object: true,
78
coerce: true
79
});
80
// Result: { data: { count: 42, active: true } }
81
82
// Force array notation for consistent structure
83
const arrays = parser.toJson('<list><item>a</item><item>b</item></list>', {
84
object: true,
85
arrayNotation: true
86
});
87
88
// Custom text node property
89
const custom = parser.toJson('<tag>text content</tag>', {
90
object: true,
91
alternateTextNode: 'text'
92
});
93
```
94
95
### JSON to XML Conversion
96
97
Converts JSON strings or JavaScript objects to XML format.
98
99
```javascript { .api }
100
/**
101
* Converts JSON to XML string
102
* @param {String|Object} json - JSON string or JavaScript object to convert
103
* @param {Object} options - Configuration options for conversion
104
* @returns {String} XML string
105
*/
106
function toXml(json, options);
107
```
108
109
**Parameters:**
110
- `json` (String|Object): JSON string or JavaScript object to convert
111
- `options` (Object, optional): Configuration options
112
113
**Returns:** String (XML)
114
115
**Usage Examples:**
116
117
```javascript
118
// Basic conversion
119
const xml = parser.toXml('{"person":{"name":"John","age":"30"}}');
120
121
// From JavaScript object
122
const xml2 = parser.toXml({ person: { name: "John", age: "30" } });
123
124
// With sanitization enabled
125
const xml3 = parser.toXml({ message: "Hello <world> & friends" }, {
126
sanitize: true
127
});
128
129
// Ignore null values
130
const xml4 = parser.toXml({ data: { value: "test", empty: null } }, {
131
ignoreNull: true
132
});
133
```
134
135
### Command Line Interface
136
137
CLI tool for converting XML to JSON from stdin to stdout.
138
139
```bash
140
# Convert XML file to JSON
141
cat file.xml | xml2json
142
143
# Check version
144
xml2json --version
145
```
146
147
The CLI reads XML from standard input and outputs JSON to standard output.
148
149
## Configuration Options
150
151
### toJson Options
152
153
```javascript { .api }
154
interface ToJsonOptions {
155
/** Return JavaScript object instead of JSON string */
156
object?: boolean;
157
/** Generate reversible JSON with $t text nodes */
158
reversible?: boolean;
159
/** Enable type coercion for numbers/booleans or provide custom coercion */
160
coerce?: boolean | Record<string, (value: string) => any>;
161
/** Sanitize special XML characters in values */
162
sanitize?: boolean;
163
/** Trim whitespace from element values */
164
trim?: boolean;
165
/** Force array notation for all elements or specific element names */
166
arrayNotation?: boolean | string[];
167
/** Change default $t text node property name */
168
alternateTextNode?: boolean | string;
169
}
170
```
171
172
**Default values:**
173
```javascript
174
{
175
object: false,
176
reversible: false,
177
coerce: false,
178
sanitize: true,
179
trim: true,
180
arrayNotation: false,
181
alternateTextNode: false
182
}
183
```
184
185
**Option Details:**
186
187
- `object` - When `true`, returns a JavaScript object instead of a JSON string
188
- `reversible` - When `true`, generates reversible JSON with `$t` text node properties for exact XML reconstruction
189
- `coerce` - When `true`, converts string values to numbers or booleans. Can be an object with custom coercion functions keyed by element/attribute names
190
- `sanitize` - When `true` (default), escapes XML special characters: `&`, `<`, `>` in element values; `&`, `<`, `>`, `"`, `'` in attribute values
191
- `trim` - When `true` (default), removes leading and trailing whitespace from element values
192
- `arrayNotation` - When `true`, treats all child elements as arrays. When an array of strings, only specified element names are treated as arrays
193
- `alternateTextNode` - When `true`, uses `_t` instead of `$t` for text nodes. When a string, uses that string as the text node property name
194
195
### toXml Options
196
197
```javascript { .api }
198
interface ToXmlOptions {
199
/** Sanitize values when converting to XML */
200
sanitize?: boolean;
201
/** Ignore null values during conversion */
202
ignoreNull?: boolean;
203
}
204
```
205
206
**Default values:**
207
```javascript
208
{
209
sanitize: false,
210
ignoreNull: false
211
}
212
```
213
214
**Option Details:**
215
216
- `sanitize` - When `true`, sanitizes values during JSON to XML conversion (default `false` for backward compatibility)
217
- `ignoreNull` - When `true`, skips null values during conversion
218
219
## Error Handling
220
221
The library throws errors in the following cases:
222
223
- **Invalid XML**: When the XML structure is malformed or cannot be parsed by node-expat
224
- **Invalid JSON**: When the JSON string cannot be parsed (for `toXml`)
225
- **Invalid Options**: When provided options don't match the expected schema (validated using joi)
226
227
```javascript
228
try {
229
const result = parser.toJson('<invalid><xml>');
230
} catch (error) {
231
console.error('XML parsing error:', error.message);
232
}
233
234
try {
235
const result = parser.toXml('invalid json string');
236
} catch (error) {
237
console.error('JSON parsing error:', error.message);
238
}
239
```
240
241
## Types
242
243
```javascript { .api }
244
/** Main parser object with conversion functions */
245
interface Parser {
246
toJson(xml: string | Buffer, options?: ToJsonOptions): string | object;
247
toXml(json: string | object, options?: ToXmlOptions): string;
248
}
249
250
/** Configuration options for XML to JSON conversion */
251
interface ToJsonOptions {
252
object?: boolean;
253
reversible?: boolean;
254
coerce?: boolean | Record<string, (value: string) => any>;
255
sanitize?: boolean;
256
trim?: boolean;
257
arrayNotation?: boolean | string[];
258
alternateTextNode?: boolean | string;
259
}
260
261
/** Configuration options for JSON to XML conversion */
262
interface ToXmlOptions {
263
sanitize?: boolean;
264
ignoreNull?: boolean;
265
}
266
```
267
268
## Text Node Handling
269
270
xml2json uses special properties to represent XML text content:
271
272
- **Default**: Text content is stored in the `$t` property
273
- **Reversible mode**: When `reversible: true`, all text content uses `$t` to ensure exact XML reconstruction
274
- **Custom text nodes**: Use `alternateTextNode` to customize the text property name
275
276
```javascript
277
// Default text handling
278
const result = parser.toJson('<tag>Hello World</tag>', { object: true });
279
// Result: { tag: { $t: "Hello World" } }
280
281
// Custom text node property
282
const custom = parser.toJson('<tag>Hello World</tag>', {
283
object: true,
284
alternateTextNode: 'text'
285
});
286
// Result: { tag: { text: "Hello World" } }
287
288
// Mixed content with attributes
289
const mixed = parser.toJson('<person name="John">Hello</person>', { object: true });
290
// Result: { person: { name: "John", $t: "Hello" } }
291
```
292
293
## Limitations
294
295
The library does not parse the following XML elements:
296
297
- CDATA sections (content is converted but structure is not reversible)
298
- Processing instructions
299
- XML declarations
300
- Entity declarations
301
- Comments
302
303
These elements are either ignored or converted to JSON without preserving their XML-specific semantics.