Skip to content

Instantly share code, notes, and snippets.

@mjackson
Created April 9, 2010 18:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjackson/361448 to your computer and use it in GitHub Desktop.
Save mjackson/361448 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>XML.js Test</title>
<script type="text/javascript" src="xml.js"></script>
<script type="text/javascript">
var xml = new XML('root');
xml.attr('one', 1);
var child = xml.child('child');
child.attr('two', 2);
child.text = 'some text here';
console.log(xml.toString());
</script>
</head>
<body></body>
</html>
function XML(name, text) {
this.name = name;
this.text = text || null;
this.attributes = {};
this.children = [];
}
XML.prototype.attr = function(name, value) {
this.attributes[name] = value;
return this;
}
XML.prototype.child = function(xml) {
if (typeof xml == "string") {
xml = new XML(xml);
}
this.children.push(xml);
return xml;
}
XML.prototype.toString = function() {
var str = "<" + this.name;
var attrs = [];
for (var name in this.attributes) {
attrs.push(name + "=\"" + this.attributes[name] + "\"");
}
if (attrs.length > 0) {
str += " " + attrs.join(" ");
}
if (this.text == null && this.children.length == 0) {
str += "/";
} else {
str += ">";
if (this.text != null) {
str += this.text;
}
for (var i = 0, len = this.children.length; i < len; ++i) {
str += this.children[i].toString();
}
str += "</" + this.name;
}
str += ">";
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment