node.jsxmlxml-parsingbody-parserxml2js

Node.js - Xml Parsing


I have used many xml parsers till now, but non of them helps me to achieve my objective. A list of parsers that I've used is xml-body-parser, xml2js, libxmljs and xamel.

I want to do following things

Till now, I've just accomplished to send xml and then response xml, nothing else

Code till now is

var express = require("express"), 
    bodyParser = require('body-parser');

require("body-parser-xml")(bodyParser);
var xml2js = require('xml2js');
var builder = new xml2js.Builder;
var app = express();
var util = require('util');

app.use(bodyParser.xml({

    xmlParseOptions: {
        normalize: false,    
        normalizeTags: false, 
        explicitArray: false
    }
}));


var XmlPosted;
app.post('/users', function (req, res, body) {
    XmlPosted = req.body;
    console.log();
    res.send(builder.buildObject(req.body));
    res.status(200).end();
});

app.listen(4000);

Solution

  • This code works fine for me, things done in this code are

    1. Specific xml tags are searched and then new attributes are being set
    2. XML was parsed
    3. Updated response is sent

      var DOMParser = new (require('xmldom')).DOMParser({ normalizeTags: { default: false } });
      var express = require("express"),
          bodyParser = require('body-parser');
      require("body-parser-xml")(bodyParser);
      var xml2js = require('xml2js');
      var builder = new xml2js.Builder({ standalone: { default: false } });
      var app = express();
      //Options of body-parser-xml module
      
      app.use(bodyParser.xml({
          xmlParseOptions: {
              normalize: false,     // Trim whitespace inside text nodes
              normalizeTags: false, // Transform tags to lowercase
              explicitArray: false // Only put nodes in array if >1
          }
      }));
      
      //Post Method
      app.post('/users', function (req, res, body) {
      
          //Parsing Request.Body
          var document = DOMParser.parseFromString(
              builder.buildObject(req.body).toString()
          );
          //Getting a list of elements whose name is being given
          var node = document.getElementsByTagName("TextView");
      
          //Changing Tag Name of Specific Elements
          for (var i = 0; i < node.length; i++) {
              node[i].tagName = "com.mycompany.projectname.TextView";
          }
          //Responsing Updated Data
          res.send(document.toString());
      });
      app.listen(1000);