Posted By

mb2o on 04/15/11


Tagged

xml json convert


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

mb2o


XML to JSON


 / Published in: JavaScript
 

  1. // Changes XML to JSON
  2. function xmlToJson(xml) {
  3.  
  4. // Create the return object
  5. var obj = {};
  6.  
  7. if (xml.nodeType == 1) { // element
  8. // do attributes
  9. if (xml.attributes.length > 0) {
  10. obj["@attributes"] = {};
  11. for (var j = 0; j < xml.attributes.length; j++) {
  12. var attribute = xml.attributes.item(j);
  13. obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
  14. }
  15. }
  16. } else if (xml.nodeType == 3) { // text
  17. obj = xml.nodeValue;
  18. }
  19.  
  20. // do children
  21. if (xml.hasChildNodes()) {
  22. for(var i = 0; i < xml.childNodes.length; i++) {
  23. var item = xml.childNodes.item(i);
  24. var nodeName = item.nodeName;
  25. if (typeof(obj[nodeName]) == "undefined") {
  26. obj[nodeName] = xmlToJson(item);
  27. } else {
  28. if (typeof(obj[nodeName].length) == "undefined") {
  29. var old = obj[nodeName];
  30. obj[nodeName] = [];
  31. obj[nodeName].push(old);
  32. }
  33. obj[nodeName].push(xmlToJson(item));
  34. }
  35. }
  36. }
  37. return obj;
  38. };

Report this snippet  

You need to login to post a comment.