9

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);
}
2
  • Both JSON and XML should have a root element (unless the JSON is an array that is, but then you should not try to convert it to XML). It would be wise to provide an example JSON and the resulting XML in the question, just to illustrate it better. Commented Jul 7, 2016 at 11:43
  • Wait, you're making the JSON->XML using xml2js.Builder() not xml2js.Parser(), right? Commented Jul 7, 2016 at 12:24

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

This is too long for a comment.

The correct way to create XML from JSON with xml2js is using xml2js.Builder. For example, in the following snippet the JSON is changed into an XML string and then parsed back to JSON:

var fs = require('fs');
var xml2js = require('xml2js');

var data = { VAST: { '$': { version: '2.0' }
                   , Ad: { '$': { id: '72419' }, content: "yay" } } };
console.log("the JSON");
console.log(JSON.stringify(data));

// the JSON
// {"VAST":{"$":{"version":"2.0"},"Ad":{"$":{"id":"72419"},"content":"yay"}}}

var builder = new xml2js.Builder();
var xml = builder.buildObject(data);
console.log("result from xml2js.builder");
console.log(xml);  // this is a string

// result from xml2js.builder
// <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
// <VAST version="2.0">
//   <Ad id="72419">
//     <content>yay</content>
//   </Ad>
// </VAST>

var parser = new xml2js.Parser();
parser.parseString(xml, function(err, result) {
    console.log("result of parsing it back");
    console.log(JSON.stringify(result));
    console.log(result.VAST['Ad'][0]['$']['id']);  // you can get the id back
  });

// result of parsing it back
// {"VAST":{"$":{"version":"2.0"},"Ad":[{"$":{"id":"72419"},"content":["yay"]}]}}
// 72419

The parser adds an extra array ("Ad":[{"$") because you can have more than one Ad tag (and this allows for a clean way to access things in node later).


Now, if you add this:

var badxml = builder.buildObject(xml);
console.log(badxml);

To the end of that snippet then you do get an XML with an extra root element:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
&lt;VAST version="2.0"&gt;
  &lt;Ad id="72419"&gt;
    &lt;content&gt;yay&lt;/content&gt;
  &lt;/Ad&gt;
&lt;/VAST&gt;</root>

But it is still quite different from what you are getting, since it is properly escaped.

1 Comment

I'm manipulating XML with xml2js and adding new nodes and then converting back it to XML (from JSON)
1

for someone who use js2xmlparser,

const xml = js2xmlparser.parse("envelope_tag", {response : myJsonData}, {declaration: {include:false}})

res.send(xml);

i put this here because this is the one question about xml - json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.