Created
March 27, 2011 19:44
-
-
Save cjcliffe/889524 to your computer and use it in GitHub Desktop.
XML Dom to Badgerfish JSON
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
function xml2badgerfish(xmlDoc) { | |
var jsonData = {}; | |
var nodeStack = []; | |
var i, iMax, iMin; | |
var n = xmlDoc; | |
var j = jsonData; | |
var cn, tn; | |
var regEmpty = /^\s+|\s+$/g; | |
xmlDoc.jsonParent = j; | |
nodeStack.push(xmlDoc); | |
while (nodeStack.length) { | |
var n = nodeStack.pop(); | |
var tagGroup = null; | |
j = n.jsonParent; | |
for (i = 0, iMax = n.childNodes.length; i < iMax; i++) { | |
cn = n.childNodes[i]; | |
tn = cn.tagName; | |
if (tn !== undef) { | |
tagGroup = tagGroup || {}; | |
tagGroup[tn] = tagGroup[tn] || 0; | |
tagGroup[tn]++; | |
} | |
} | |
if (n.attributes) if (n.attributes.length) { | |
for (i = 0, iMax = n.attributes.length; i < iMax; i++) { | |
var att = n.attributes[i]; | |
j["@" + att.name] = att.value; | |
} | |
} | |
for (i = 0, iMax = n.childNodes.length; i < iMax; i++) { | |
cn = n.childNodes[i]; | |
tn = cn.tagName; | |
if (cn.nodeType === 1) { | |
if (tagGroup[tn] > 1) { | |
j[tn] = j[tn] || []; | |
j[tn].push({}); | |
cn.jsonParent = j[tn][j[tn].length - 1]; | |
} else { | |
j[tn] = j[tn] || {}; | |
cn.jsonParent = j[tn]; | |
} | |
nodeStack.push(cn); | |
} else if (cn.nodeType === 3) { | |
if (cn.nodeValue.replace(regEmpty, "") !== "") { | |
j.$ = j.$ || ""; | |
j.$ += cn.nodeValue; | |
} | |
} | |
} | |
} | |
return jsonData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment