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);
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With