Skip to content
Advertisement

JSON to XML Using Javascript

I am trying to convert the JSON to XML but not getting exact output.In My JSON having array object it not converting that to XML array.Mainly array object is not converting into XML as expected

var InputJSON = "{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}";
var output = eval("OBJtoXML("+InputJSON+");")

function OBJtoXML(obj) {
    var xml = '';
    for (var prop in obj) {
        xml += "<" + prop + ">";
        if(obj[prop] instanceof Array) {
            for (var array in obj[prop]) {
                xml += OBJtoXML(new Object(obj[prop][array]));
            }
        } else if (typeof obj[prop] == "object") {
            xml += OBJtoXML(new Object(obj[prop]));
        } else {
            xml += obj[prop];
        }
        xml += "</" + prop + ">";
    }
    var xml = xml.replace(/</?[0-9]{1,}>/g,'');
    return xml
}

Actual Output:

<body>
  <entry>
    <fullURL>abcd</fullURL>
    <Resource>1234</Resource>
    <fullURL>efgh</fullURL>
    <Resource>5678</Resource>
  </entry>
</body>

Expected Output:

<body>
  <entry>
    <fullURL>abcd</fullURL>
    <Resource>1234</Resource>
  </entry>
 <entry>
    <fullURL>efgh</fullURL>
    <Resource>5678</Resource>
  </entry>
</body>

Please guide me if i am missing anything from the code to get my expected result

Advertisement

Answer

replace your OBJtoXML function with

function OBJtoXML(obj) {
  var xml = '';
  for (var prop in obj) {
    xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
    if (obj[prop] instanceof Array) {
      for (var array in obj[prop]) {
        xml += "<" + prop + ">";
        xml += OBJtoXML(new Object(obj[prop][array]));
        xml += "</" + prop + ">";
      }
    } else if (typeof obj[prop] == "object") {
      xml += OBJtoXML(new Object(obj[prop]));
    } else {
      xml += obj[prop];
    }
    xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
  }
  var xml = xml.replace(/</?[0-9]{1,}>/g, '');
  return xml
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement