Created
February 12, 2011 12:03
-
-
Save tanepiper/823717 to your computer and use it in GitHub Desktop.
xml2json
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 sys = require('sys'), fs = require('fs'), libxml = require('./libxmljs'); | |
var stack = []; | |
var parser = new libxml.SaxPushParser(function(cb) { | |
cb.onStartDocument(function() { | |
sys.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 { | |
sys.log('Done!'); | |
sys.puts(sys.inspect(obj, false, 1)); | |
} | |
}); | |
cb.onCharacters(function(chars) { | |
chars = chars.trim(); | |
if (chars != "") | |
stack[stack.length-1]['#'] += chars; | |
}); | |
}); | |
var fstream = fs.createReadStream("foo.xml", { 'flags': 'r', 'encoding': 'utf8', 'mode': 0666, 'bufferSize': 4096 }); | |
fstream.addListener('data', function(chunk) { | |
parser.push(chunk.toString()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment