Created
May 22, 2011 13:05
-
-
Save ixth/985445 to your computer and use it in GitHub Desktop.
Library for xml to json conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
fuck copyrights, i just need working lib | |
*/ | |
(function (global) { | |
function serializeNode(xmlNode) { | |
var jsonNode = {}; | |
if (xmlNode.attributes) { | |
for (var i = 0, length = xmlNode.attributes.length; i < length; i++) { | |
jsonNode[xmlNode.attributes[i].name] = xmlNode.attributes[i].value | |
} | |
} | |
var preliminaryCache = {}; | |
for (var i = 0, length = xmlNode.childNodes.length; i < length; i++) { | |
var currentNode = xmlNode.childNodes[i]; | |
if (typeof preliminaryCache[currentNode.nodeName] == 'undefined') { | |
preliminaryCache[currentNode.nodeName] = []; | |
} | |
preliminaryCache[currentNode.nodeName].push(serializeNode(xmlNode.childNodes[i])); | |
} | |
for (var name in preliminaryCache) { | |
if (preliminaryCache[name].length > 1) { | |
jsonNode[name] = preliminaryCache[name]; | |
} else if (preliminaryCache[name].length == 1) { | |
jsonNode[name] = preliminaryCache[name][0]; | |
} | |
} | |
return jsonNode; | |
} | |
global.xml2json = { | |
parse: function (xml) { | |
if (!(xml instanceof Document)) { | |
var parser = new DOMParser(); | |
xml = parser.parseFromString(xml, 'text/xml'); | |
} | |
return serializeNode(xml); | |
} | |
}; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment