Skip to content

Instantly share code, notes, and snippets.

@carloscarucce
Created February 16, 2018 12:23
Show Gist options
  • Save carloscarucce/8a05de4fe4c22849703c03dbfbc99ea0 to your computer and use it in GitHub Desktop.
Save carloscarucce/8a05de4fe4c22849703c03dbfbc99ea0 to your computer and use it in GitHub Desktop.
XmlElement (creates xml in javascript)
var xml = new XmlElement("teste", function(el, at, text){
el("sub1", "test");
el("sub2", function(el, at, text){
at("name", "John Doe");
text("123");
});
el("sub3", function(el, at, text){
el("sub4", function(el, at, text){
at("val", "something");
at("val2", "something else");
text('test');
});
});
});
console.log(xml.toString());
/**
* Represents a XML element
*
* @param {string} elementName
* @param {string|function} contentBuilder
* @constructor
*/
var XmlElement = function(elementName, contentBuilder) {
var name = elementName;
var text = '';
var attributes = [];
var elements = [];
var _self = this;
/**
*
* @param {string} name
* @param {string} value
*/
this.addAttribute = function (name, value) {
attributes.push({name: name, value: value});
};
/**
*
* @param name
* @param {string|function} contentBuilder
*/
this.createElement = function (name, contentBuilder) {
var el = new XmlElement(name, contentBuilder);
elements.push(el);
};
/**
*
* @param {string} txt
*/
this.setText = function(txt) {
text = "<![CDATA[" + txt + "]]>";
};
/**
*
* @returns {string}
*/
this.toString = function() {
var attrsString = "";
attributes.forEach(function(attr) {
attrsString += " " + attr.name + "=\"" + attr.value + "\"";
});
var str = "<" + name;
str += attrsString;
if (text.length == 0 && elements.length == 0) {
str += " />"
} else {
str += ">";
var subElementsStr = "";
elements.forEach(function(el){
str += el.toString();
});
str += text;
str += "</" + name + ">";
}
return str;
}
//Construct
if (!name) {
throw "'name' parameter is required";
}
contentBuilder = contentBuilder || '';
if ((typeof contentBuilder) === "function") {
contentBuilder(_self.createElement, _self.addAttribute, _self.setText);
} else {
_self.setText(contentBuilder);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment