Skip to content

Instantly share code, notes, and snippets.

@jscheel
Created March 23, 2011 12:43
Show Gist options
  • Save jscheel/883044 to your computer and use it in GitHub Desktop.
Save jscheel/883044 to your computer and use it in GitHub Desktop.
var fs = require('fs'), libxml = require('./libxmljs');
var parser = new libxml.SaxPushParser(function(cb) {
var stack = [];
cb.onStartDocument(function() {
console.log('Starting to parse ...');
});
cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {
var obj = {};
obj['@'] = {};
obj['#'] = "";
for (var i=0,len=attrs.length; i<len; i++)
obj['@'][attrs[i][0]] = attrs[i][3];
stack.push(obj);
});
cb.onEndElementNS(function(elem, prefix, uri) {
var obj = stack.pop();
if (stack.length > 0) {
if (typeof stack[stack.length-1][elem] === 'undefined')
stack[stack.length-1][elem] = obj;
else if (Array.isArray(stack[stack.length-1][elem]))
stack[stack.length-1][elem].push(obj);
else {
var old = stack[stack.length-1][elem];
stack[stack.length-1][elem] = [];
stack[stack.length-1][elem].push(old);
}
} else {
console.log('Finished parsing. Result:');
console.dir(obj);
}
});
cb.onCharacters(function(chars) {
chars = chars.trim();
if (chars.length)
stack[stack.length-1]['#'] += chars;
});
});
var fstream = fs.createReadStream('foo.xml', { encoding: 'utf8' });
fstream.on('data', function(chunk) {
parser.push(chunk);
});
@jscheel
Copy link
Author

jscheel commented Mar 23, 2011

Just wanted a permanent copy for myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment