Skip to content

Instantly share code, notes, and snippets.

@cjcliffe
Created March 27, 2011 19:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjcliffe/889524 to your computer and use it in GitHub Desktop.
Save cjcliffe/889524 to your computer and use it in GitHub Desktop.
XML Dom to Badgerfish JSON
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