obj-to-xml
Version:
This module converts any object into an XML
50 lines (49 loc) • 1.72 kB
JavaScript
exports.buildXmlFromObj = function (obj, strOutput) {
/* Pass an object to create an xml.
Format ->
ROOT: {
R: {
'@id': 1
}
}
creates an xml -> <ROOT> <R id="1"/> </ROOT>
Property which is defined with @, is treated as an attribute.
strOutput: Pass true to return XML in string format.
*/
function removeSpacesFromTags (str) {
var regEx = new RegExp(' ', 'g');
return str.replace(regEx, '-');
}
var xmlOutput = function xmlFromObj(obj, xml) {
var rootKey = Object.keys(obj),
metaXml, keyElem, objValue, i, j;
function createChildTag(objVal) {
metaXml = document.createElementNS('', removeSpacesFromTags(keyElem));
metaXml = xmlFromObj(objVal, metaXml);
if (xml) {
xml.appendChild(metaXml);
} else {
xml = metaXml;
}
return xml;
}
for (i = 0; i < rootKey.length; i++) {
keyElem = removeSpacesFromTags(rootKey[i]);
objValue = obj[rootKey[i]];
if (keyElem.index('@') > -1) {
xml.setAttributeNS('', keyElem.slice(1, keyElem.length), objValue);
}
if (typeof objValue == 'object') {
if (Array.isArray(objValue)) {
for (j = 0; j < objValue.length; j++) {
xml = createChildTag(objValue[j]);
}
} else {
xml = createChildTag(objValue);
}
}
}
return xml;
}(obj);
return strOutput ? new XMLSerializer().serializeToString(xmlOutput) : xmlOutput;
}