JSFiddle - React, Tailwind, and code Playground
JavaScript
// module namespace
var MyApp = {
"util": {}
};
// inputs:
// options: a option hash
// options[root]: xml root tag, "root" if unspecified
// obj: the hash to be converted
// obj cannot contain functions at any level
//
// output:
// -1 if parsing failed
// a XML string if parsing successful
MyApp.util.toXML = function(options, obj) {
// inner function for recursion
var obj_to_xml = function(obj) {
var result = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result.push("<" + key + ">");
var val = obj[key];
if (val instanceof Function) {
return -1;
} else if (val != null && val instanceof Object) {
// since null is also an object, avoid passing it to recursion
var val_result = obj_to_xml(val);
if (val_result === -1) {
return -1;
}
result = result.concat(val_result);
} else {
result.push(val + "");
}
result.push("</" + key + ">");
}
}
return result;
};
var options = options || {};
var root = options["root"] || "root";
// uses an array of strings and joining only in the end to reduce memory usage
var result = [];
result.push("<" + root + ">");
var obj_result = obj_to_xml(obj);
if (obj_result === -1) {
return -1;
}
result = result.concat(obj_result);
result.push("</" + root + ">");
return result.join("");
};
// uses function currying to attach MyApp.util.toXML to Object prototype
// caches original toXML inside the closure to allow retrieval via unload
(function(toXML) {
alert(1);
var savedToXML;
toXML.load = function() {
savedToXML = Object.prototype.toXML;
Object.prototype.toXML = function(options) {
...