malkomalko
7/3/2010 - 12:37 AM

gistfile1.js

var sys = require('sys'),
fs = require('fs'),
b = require('buffer');
var 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 (stack[stack.length-1][elem] instanceof Array)
			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) {
	if (chars.trim() != "")
		stack[stack.length-1]['#'] += chars.trim();
  });
});

var fstream = fs.createReadStream("products.xml", { 'flags': 'r', 'encoding': 'utf8', 'mode': 0666, 'bufferSize': 4096 });
fstream.addListener('data', function(chunk) {
	parser.push(chunk.toString());
});