Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Created July 6, 2009 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atesgoral/141604 to your computer and use it in GitHub Desktop.
Save atesgoral/141604 to your computer and use it in GitHub Desktop.
function xmlEscape(s) {
return s.replace(/[<>&"]/g, function (c) {
return "&"
+ { "<": "lt", ">": "gt", "&": "amp", "\"": "quot" }[c]
+ ";";
});
}
var xml = [ "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ];
xml.text = function () {
Array.prototype.push.apply(this, arguments);
return this;
};
xml.elem = function (tagName, attrs, selfClose) {
this.text("<", tagName);
for (var a in attrs || {}) {
this.text(" ", a, "=\"", xmlEscape(String(attrs[a])), "\"");
}
this.text(selfClose ? "/" : "", ">\n");
return this;
};
xml.toString = function () { return this.join(""); }
/* Usage */
// Add an element with attributes
xml.elem("root", { attrib1: "hello", attrib2: "world" });
// Add a self-closing element (as child of previous)
xml.elem("child", { attrib: 42 }, true);
// Add some nested children
xml.elem("child").elem("nested", {}, true).elem("/child");
// Note that calls to elem() and text() can be chained
// Add an element with text content
xml.elem("child", {}).text("Hello World!").elem("/child");
// Close the root node
xml.elem("/root");
// Get the generated XML
alert(xml);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment