Posted by & filed under Node.js.

Here’s an NPM Module I came up with which can convert a javascript object to XML, EasyXML. There’s a few of them out there already, but they lacked some configurability that I desired, specificially the ability to have pluralized/singular parent/children for array objects (a convention we use at work). The name of the module is `easyxml`, and can be installed like so:

npm install easyxml

Here is some example code for configuring your converter. This is a universal thing and only needs to be done once.

var easyxml = require('easyxml');
easyxml.configure({
  singularizeChildren: true,
  underscoreAttributes: true,
  rootElement: 'response',
  dateFormat: 'ISO',
  indent: 2,
  manifest: true
});

The main purpose of this module was to be used for an API, which would respond with either JSON or XML depending on what the client asked for. Use this code if you would like to use this module in a similar way.

app.use(function(req, res, next) {
    res.sendData = function(obj) {
        if (req.accepts('json') || req.accepts('text/html')) {
            res.header('Content-Type', 'application/json');
            res.send(obj);
        } else if (req.accepts('application/xml')) {
            res.header('Content-Type', 'text/xml');
            var xml = easyxml.render(obj);
            res.send(xml);
        } else {
            res.send(406);
        }
    };

    next();
});

When you’re prepared to send your object to the client, you use res.sendData(obj) instead of res.send(obj).

res.status(200).sendData(obj);

If you find any bugs in the module, report them as issues and I will attempt to fix it. There are certain ambiguous documents which can’t be easily converted into XML. When you find these documents, put them into a bug report along with your expected XML output. And as always, you can also submit a pull request with a fix ;).

Thomas Hunter II

Thomas is the author of Advanced Microservices and a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.

Latest posts by Thomas Hunter II (see all)

Tags: