f748b0d7-1a09-49c5-a816-3e1986d9e9d8

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:

–save: to save to Package.json file

npm install easyxml --save

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');

var serializer = new easyxml({
    singularizeChildren: true,
    allowAttributes: true,
    rootElement: 'response',
    dateFormat: 'ISO',
    indent: 2,
    manifest: true
});

app.use(function (req, res, next) {
    res.sendData = function (obj) { //Ham res.sendData tu custom
        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 = serializer.render(obj);
            res.send(xml);
        } else {
            res.sendStatus(406);
        }
    };
    next();
});


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

app.get("/testget", function (req, res, next) {
    res.status(200).sendData({
       Test: "abc",
       test2: "def"
    });
});

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 ;).

JSON, XML in NodeJS API
Test get XML in NodeJS API

Respond to JSON or XML requests from a Node.js API

Category: NodeJSPrograming
0
2904 views

Join the discussion

Your email address will not be published. Required fields are marked *