Created
April 9, 2010 18:40
-
-
Save mjackson/361448 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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