aboutsummaryrefslogtreecommitdiff
path: root/lib/xml/nodes.js
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2015-08-16 14:21:25 +0100
committerMichael Williamson <mike@zwobble.org>2015-08-16 14:22:46 +0100
commit9ff57bb770e0296bb2f5b7a41711c53954eb8c4e (patch)
tree048868d884058f59ed54b41f560d9c234de67c62 /lib/xml/nodes.js
parent883af29dfdbf98d1e0a61d459ffeb08b0b5a34a6 (diff)
Split xmlreader into nodes and reader modules
Diffstat (limited to 'lib/xml/nodes.js')
-rw-r--r--lib/xml/nodes.js60
1 files changed, 60 insertions, 0 deletions
diff --git a/lib/xml/nodes.js b/lib/xml/nodes.js
new file mode 100644
index 0000000..ed273cf
--- /dev/null
+++ b/lib/xml/nodes.js
@@ -0,0 +1,60 @@
+var _ = require("underscore");
+
+
+exports.Element = Element;
+
+
+var emptyElement = {
+ first: function() {
+ return null;
+ },
+ firstOrEmpty: function() {
+ return emptyElement;
+ },
+ attributes: {}
+};
+
+function Element(name, attributes, children) {
+ this.type = "element";
+ this.name = name;
+ this.attributes = attributes || {};
+ this.children = children || [];
+}
+
+Element.prototype.first = function(name) {
+ return _.find(this.children, function(child) {
+ return child.name == name;
+ });
+};
+
+Element.prototype.firstOrEmpty = function(name) {
+ return this.first(name) || emptyElement;
+};
+
+Element.prototype.getElementsByTagName = function(name) {
+ var elements = _.filter(this.children, function(child) {
+ return child.name == name;
+ });
+ return toElementList(elements);
+};
+
+Element.prototype.text = function() {
+ if (this.children.length === 0) {
+ return "";
+ } else if (this.children.length !== 1 || this.children[0].type !== "text") {
+ throw new Error("Not implemented");
+ }
+ return this.children[0].value;
+};
+
+var elementListPrototype = {
+ getElementsByTagName: function(name) {
+ return toElementList(_.flatten(this.map(function(element) {
+ return element.getElementsByTagName(name);
+ }, true)));
+ }
+};
+
+function toElementList(array) {
+ return _.extend(array, elementListPrototype);
+}