xml-js
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
sax | 1.3.0 | 14.99 kB | ISC | prod |
The npm package "xml-js" serves as a converter between XML text and JavaScript objects or JSON text. It allows users to transform XML text into JavaScript objects or JSON text and vice versa while maintaining the order of elements. The functionality spans to include handling of elements, attributes, texts, comments, CData, DOCTYPE, XML declarations, and Processing Instructions, while also extending support to command-line operations.
To use the xml-js package, you first need to install it via npm using the command npm install --save xml-js
. Once installed, it can be imported into your JavaScript file with var convert = require('xml-js');
.
You can then convert XML to JSON with:
var xml = '<root>Hello xml-js</root>';
var result = convert.xml2json(xml, {compact: true, spaces: 4});
console.log(result);
And JSON to XML with:
var json = { "_declaration": { "_attributes": { "version": "1.0", "encoding": "utf-8" } }, "root": { "_text": "Hello xml-js" } };
var result = convert.json2xml(json, {compact: true, spaces: 4});
console.log(result);
Please note that in the example above, the xml2json()
and json2xml()
functions are used with compact mode enabled, where the XML is represented compactly as {"a":{}}
as opposed to non-compact output {"elements":[{"type":"element","name":"a"}]}
.
The xml-js documentation with detailed API reference and usage examples can be found on the xml-js GitHub page here. It covers installation, quick start code, sample conversions, API reference, command-line usage, and more in extensive detail.