Skip to content

Instantly share code, notes, and snippets.

@MorningZ
Created May 10, 2011 18:30
Show Gist options
  • Save MorningZ/965080 to your computer and use it in GitHub Desktop.
Save MorningZ/965080 to your computer and use it in GitHub Desktop.
Function to convert XML data to easier-to-work-with JSON
/*
I take zero credit for this, as it was posted as a comment on this blog post:
http://davidwalsh.name/convert-xml-json
*/
function xml2Obj (oXMLDom) {
var oRObj = true;
if (oXMLDom.nodeType === 3) { // text
oRObj = oXMLDom.nodeValue.replace(/^\s+|\s+$/g, "");
} else {
if (oXMLDom.nodeType === 1) { // element
// do attributes
if (oXMLDom.attributes.length > 0) {
var iAttrib;
oRObj = {};
oRObj["@attributes"] = {};
for (var iAttrId = 0; iAttrId < oXMLDom.attributes.length; iAttrId++) {
iAttrib = oXMLDom.attributes.item(iAttrId);
oRObj["@attributes"][iAttrib.nodeName] = iAttrib.nodeValue;
}
}
}
// do children
if (oXMLDom.hasChildNodes()) {
var iKey, iValue, iXMLNode;
if (oRObj === true) { oRObj = {}; }
for (var iChildId = 0; iChildId < oXMLDom.childNodes.length; iChildId++) {
iXMLNode = oXMLDom.childNodes.item(iChildId);
iKey = iXMLNode.nodeType === 3 ? "@content" : iXMLNode.nodeName;
iValue = xml2Obj(iXMLNode);
if (oRObj.hasOwnProperty(iKey)) {
if (iXMLNode.nodeType === 3) { oRObj[iKey] += iValue; }
else {
if (oRObj[iKey].constructor !== Array) { oRObj[iKey] = [oRObj[iKey]]; }
oRObj[iKey].push(iValue);
}
} else if (iXMLNode.nodeType !== 3 || iValue !== "") { oRObj[iKey] = iValue; }
}
}
}
return(oRObj);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment