Skip to content

Instantly share code, notes, and snippets.

@qetr1ck-op
Created November 2, 2015 18:32
Show Gist options
  • Save qetr1ck-op/cb9ab4fbc5f4debf8ce8 to your computer and use it in GitHub Desktop.
Save qetr1ck-op/cb9ab4fbc5f4debf8ce8 to your computer and use it in GitHub Desktop.
function xml() {
return {
toJSONObject: function(xml) {
return (xml ? toJSON(xml) : xml);
},
fromJSONObject: function(json) {
return this.fromString(toXML(json));
},
toString: function(obj) {
return (obj ? (new XMLSerializer()).serializeToString(obj.nodeType === undefined ? this.fromJSONObject(obj) : obj) : '');
},
fromString: function(str) {
return (str.charAt(0) == '<' ? (new DOMParser()).parseFromString(str.trim(), 'text/xml') : toXML(window.JSON.parse(str)));
}
};
function toJSON(xml) {
let obj = {};
let attr;
// object type
if (xml.nodeType == 1) { // element
if (xml.attributes && (xml.attributes.length > 0)) {
obj['#attributes'] = {};
for (let i = 0; i < xml.attributes.length; i++) {
attr = xml.attributes.item(i);
obj['#attributes'][attr.nodeName] = attr.nodeValue;
}
}
} else if (xml.nodeType == 3) // text
obj = xml.nodeValue;
// do children
if (xml.hasChildNodes()) {
for (let i = 0; i < xml.childNodes.length; i++) {
let vItem = xml.childNodes.item(i),
vNodeName = vItem.nodeName;
if (typeof(obj[vNodeName]) == 'undefined') obj[vNodeName] = toJSON(vItem);
else {
if (typeof(obj[vNodeName].length) == 'undefined') {
let vOld = obj[vNodeName];
obj[vNodeName] = [];
obj[vNodeName].push(vOld);
}
obj[vNodeName].push(toJSON(vItem));
}
}
}
return obj;
}
function toXML(json, pTagName) {
const vAttrList = [];
let attrs = {};
let vInnerXML = '';
if (attrs = json['#attributes'])
for (let attr in attrs)
vAttrList.push(attr + '="' + attrs[attr] + '"');
if (!(vInnerXML = json['#text'])) {
let vInnerList = [];
for (let vPrp in json)
if (vPrp.charAt(0) != '#')
vInnerList.push(toXML(json[vPrp], vPrp));
vInnerXML = vInnerList.join('\r\n');
}
if (pTagName)
return '<' + pTagName + ' ' + vAttrList.join(' ') + '>' + vInnerXML + '</' + pTagName + '>';
else
return vInnerXML;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment