aboutsummaryrefslogtreecommitdiff
path: root/lib/xmlreader.js
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2013-03-29 18:57:02 +0000
committerMichael Williamson <mike@zwobble.org>2013-03-29 18:57:02 +0000
commit504f59e38e57b543ac87f73df53fe3a6ba34e26d (patch)
treeec6b292b8d16169e9b957864b1c3be369eb6d54d /lib/xmlreader.js
Very basic conversion from docx to HTML
Diffstat (limited to 'lib/xmlreader.js')
-rw-r--r--lib/xmlreader.js75
1 files changed, 75 insertions, 0 deletions
diff --git a/lib/xmlreader.js b/lib/xmlreader.js
new file mode 100644
index 0000000..67dda38
--- /dev/null
+++ b/lib/xmlreader.js
@@ -0,0 +1,75 @@
+var q = require("q");
+var sax = require("sax");
+var _ = require("underscore");
+
+exports.read = read;
+
+function read(xmlString) {
+ var parser = sax.parser(true, {xmlns: true, position: false});
+
+ //~ parser.onerror = function(error) {
+ //~ Q.fcall(function () {
+ //~ throw new Error("Can't do it");
+ //~ });
+ //~ };
+
+ var rootElement = {children: []};
+ var currentElement = rootElement;
+ var stack = [];
+
+ var deferred = q.defer();
+
+ parser.onopentag = function(node) {
+ var attributes = mapValues(node.attributes, function(attribute) {
+ return attribute.value;
+ });
+
+ var element = new Element(node.name, attributes);
+ currentElement.children.push(element);
+ stack.push(currentElement);
+ currentElement = element
+ };
+
+ parser.onclosetag = function(node) {
+ currentElement = stack.pop();
+ };
+
+ parser.ontext = function(text) {
+ if (currentElement !== rootElement) {
+ currentElement.children.push({
+ type: "text",
+ value: text
+ });
+ }
+ };
+
+ parser.onend = function() {
+ deferred.resolve({
+ root: rootElement.children[0]
+ });
+ };
+
+ parser.write(xmlString).close();
+
+ return deferred.promise;
+}
+
+function mapValues(input, mapper, context) {
+ return _.reduce(input, function (obj, v, k) {
+ obj[k] = mapper.call(context, v, k, input);
+ return obj;
+ }, {}, context);
+}
+
+function Element(name, attributes) {
+ this.type = "element";
+ this.name = name;
+ this.attributes = attributes;
+ this.children = [];
+}
+
+Element.prototype.first = function(name) {
+ return _.find(this.children, function(child) {
+ return child.name == name;
+ });
+}