What is xml2js?
The xml2js npm package is a library that allows users to convert XML data into a JavaScript object and vice versa. It is useful for working with XML data in a JavaScript environment, such as Node.js applications, where JSON is the more commonly used data format.
What are xml2js's main functionalities?
Parsing XML to JavaScript Object
This feature allows you to parse XML data and convert it into a JavaScript object. The 'parseString' method takes an XML string and a callback function that receives the parsed result.
const xml2js = require('xml2js');
const parser = new xml2js.Parser();
const xml = '<root>Hello xml2js!</root>';
parser.parseString(xml, (err, result) => {
console.log(result);
});
Converting JavaScript Object to XML
This feature enables you to take a JavaScript object and convert it into an XML string. The 'Builder' class is used to create an XML string from the provided object.
const xml2js = require('xml2js');
const builder = new xml2js.Builder();
const obj = { root: 'Hello xml2js!' };
const xml = builder.buildObject(obj);
console.log(xml);
Customizing Parser Options
xml2js allows you to customize the behavior of the parser through various options. In this example, 'explicitArray' is set to false to avoid wrapping single elements in an array, and 'trim' is set to true to trim the whitespace from the text nodes.
const xml2js = require('xml2js');
const parser = new xml2js.Parser({
explicitArray: false,
trim: true
});
const xml = '<root> Hello xml2js! </root>';
parser.parseString(xml, (err, result) => {
console.log(result);
});
Other packages similar to xml2js
fast-xml-parser
fast-xml-parser is an npm package that provides similar XML parsing and building functionalities as xml2js. It is known for its speed and offers a variety of options for parsing, including the ability to validate XML. It can be a faster alternative to xml2js for large XML files or performance-critical applications.
libxmljs
libxmljs is a Node.js package that binds to the libxml C library. It provides XML parsing and serialization, XPath support, and schema validation. Compared to xml2js, libxmljs is a lower-level library that may offer better performance and more advanced XML processing features but with a more complex API.
xmldom
xmldom is a W3C standard-compliant DOM parser and serializer for Node.js. It allows you to manipulate XML documents with a DOM API. While xml2js focuses on converting between XML and JavaScript objects, xmldom is more about providing a DOM interface for XML documents, which can be more familiar to developers with experience in web development.
node-xml2js
Ever had the urge to parse XML? And wanted to access the data in some sane,
easy way? Don't want to compile a C parser, for whatever reason? Then xml2js is
what you're looking for!
Description
Simple XML to JavaScript object converter. Uses
sax-js.
Note: If you're looking for a full DOM parser, you probably want
JSDom.
Installation
Simplest way to install xml2js
is to use npm, just npm install xml2js
which will download xml2js and all dependencies.
Usage
This will have to do, unless you're looking for some fancy extensive
documentation. If you're looking for every single option and usage, see the
unit tests.
Simple as pie usage
The simplest way to use it, is to use the optional callback interface added in
0.1.11. That's right, if you have been using xml-simple or a home-grown
wrapper, this is for you:
var fs = require('fs'),
xml2js = require('xml2js');
var parser = new xml2js.Parser();
fs.readFile(__dirname + '/foo.xml', function(err, data) {
parser.parseString(data, function (err, result) {
console.dir(result);
console.log('Done');
});
});
Look ma, no event listeners! Alternatively you can still use the traditional
addListener
variant:
var fs = require('fs'),
xml2js = require('xml2js');
var parser = new xml2js.Parser();
parser.addListener('end', function(result) {
console.dir(result);
console.log('Done.');
});
fs.readFile(__dirname + '/foo.xml', function(err, data) {
parser.parseString(data);
});
You can also use xml2js from
CoffeeScript, further reducing
the clutter:
fs = require 'fs',
xml2js = require 'xml2js'
parser = new xml2js.Parser()
fs.readFile __dirname + '/foo.xml', (err, data) ->
parser.parseString data, (err, result) ->
console.dir result
console.log 'Done.'
So you wanna some JSON?
Just wrap the result
object in a call to JSON.stringify
like this
JSON.stringify(result)
. You get a string containing the JSON representation
of the parsed object that you can feed to JSON-hungry consumers.
Displaying results
You might wonder why, using console.dir
or console.log
the output at some
level is only [Object]
. Don't worry, this is not because xml2js got lazy.
That's because Node uses util.inspect
to convert the object into strings and
that function stops after depth=2
which is a bit low for most XML.
To display the whole deal, you can use console.log(util.inspect(result, false, null))
, which displays the whole result.
So much for that, but what if you use
eyes for nice colored output and it
truncates the output with …
? Don't fear, there's also a solution for that,
you just need to increase the maxLength
limit by creating a custom inspector
var inspect = require('eyes').inspector({maxLength: false})
and then you can
easily inspect(result)
.
Options
Apart from the default settings, there is a number of options that can be
specified for the parser. Options are specified by new Parser({optionName: value})
. Possible options are:
explicitCharkey
(default: false
)trim
(default: true
): Trim the whitespace at the beginning and end of
text nodes.normalize
(default: true
): Trim whitespaces inside text nodes.explicitRoot
(default: false
): Set this if you want to get the root
node in the resulting object.emptyTag
(default: undefined
): what will the value of empty nodes be.
Default is {}
.explicitArray
(default: false
): Always put child nodes in an array if
true; otherwise an array is created only if there is more than one.ignoreAttrs
(default: false
): Ignore all XML attributes and only create
text nodes.mergeAttrs
(default: false
): Merge attributes and child elements as
properties of the parent, instead of keying attributes off a child
attribute object. This option is ignored if ignoreAttrs
is false
.
These default settings are for backward-compatibility (and might change in the
future). For the most 'clean' parsing, you should disable normalize
and
trimming
and enable explicitRoot
.
Running tests, development
The development requirements are handled by npm, you just need to install
them. We also have a number of unit tests, they can be run using zap
directly from the project root.