Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js remove root node from resulting XML using xml2js

Tags:

node.js

xml

I'm trying creating a XML from JSON obj and its giving me root element in the result, I tried setting the explicitRoot var parser = xml2js.Parser({explicitRoot:false}); to false but it does not remove the default root tag but just removing my orignal XML root tag (<VSAT></VSAT>)

Processing XML using xml2js

<?xml version="1.0" encoding="utf-8"?>
<VAST version="2.0">    
    <Ad id="72419"></Ad>
</VAST>

Resulting XML:

<?xml version="1.0" encoding="utf-8"?>
<root>
<VAST version="2.0">    
<Ad id="72419"></Ad>
</VAST>
</root>

Any idea ?

full code

/*
NodeJS server
*/
var http = require('http');
var xml2js = require('xml2js');
var fs = require('fs');
var util = require('util');
var json,PORT=2000;

var server = http.createServer(function(request, response){
response.writeHead(200,{'Content-Type':'text/html'});
    try{
        var filedata = fs.readFileSync('vast_all.xml','ascii');

        var parser = xml2js.Parser({explicitRoot:true});
        parser.parseString(filedata.substring(0,filedata.length),function(err,result){
            result.new = 'test';
            json = JSON.stringify(result);

            var builder = new xml2js.Builder({
                xmldec:{ 'version': '1.0', 'encoding': 'UTF-8' },
                cdata:true,
            });

            var xml = builder.buildObject(json);
            response.write(json);
            /*console.log(util.inspect(builder, false, null));*/
        });

        response.end();
    }
    catch(e){
        console.log(e);
    }
});


console.log("Server running at port "+PORT);
try{
    server.listen(PORT);
}
catch(e){
    console.log(e);
}
like image 978
AngularLearner Avatar asked Jul 07 '16 11:07

AngularLearner


2 Answers

Set the headless to true when instantiating Builder e.g.:

let builder = new xml2js.Builder({headless: true});

This worked for me. It removed the:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

But this is only supported from version 0.4.3

like image 146
Ivan Pandžić Avatar answered Sep 20 '22 07:09

Ivan Pandžić


you can't remove root node but you can change its name like this:

 let builder = new xml2js.Builder({headless: true , explicitRoot : false , rootName :'Search_Query'});
 let xml = builder.buildObject(req.param('Search_Query'));

This will change the root to Search_Query

like image 36
Salahudin Malik Avatar answered Sep 22 '22 07:09

Salahudin Malik