Created
March 23, 2011 12:43
-
-
Save jscheel/883044 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
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just wanted a permanent copy for myself.