Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add streaming

  • Loading branch information...
commit 1fa1cad4542c5a0fe7521ef6353728aa5340f5aa 1 parent ee2fecc
@evanderkoogh evanderkoogh authored
Showing with 35 additions and 3 deletions.
  1. +4 −2 lib/xml2object.js
  2. +31 −1 readme.md
View
6 lib/xml2object.js
@@ -19,7 +19,9 @@ var xml2object = module.exports = function(xmlFile, elements) {
var inObjectName;
var ancestors = [];
- this.fileStream = fs.createReadStream(xmlFile);
+ if(xmlFile) {
+ this.fileStream = fs.createReadStream(xmlFile);
+ }
this.saxStream = sax.createStream(true);
this.saxStream.on("opentag", function (args) {
@@ -127,7 +129,7 @@ var xml2object = module.exports = function(xmlFile, elements) {
});
// Rebroadcast the end of the file read
- this.fileStream.on("end", function() {
+ this.saxStream.on("end", function() {
self.emit("end");
});
};
View
32 readme.md
@@ -10,6 +10,8 @@ Converts xml elements into JavaScript objects.
## Usage
+### From a file
+
var xml2object = require('xml2object');
// Create a new xml parser with an array of xml elements to look for
@@ -29,17 +31,43 @@ Converts xml elements into JavaScript objects.
// Start parsing the XML
parser.start();
+### From a stream
+
+ var xml2object = require('xml2object');
+
+ // Create a new xml parser with an array of xml elements to look for
+ var parser = new xml2object(null, [ 'animal' ]);
+
+ // Bind to the object event to work with the objects found in the XML file
+ parser.on('object', function(name, obj) {
+ console.log('Found an object: %s', name);
+ console.log(obj);
+ });
+
+ // Bind to the file end event to tell when the file is done being streamed
+ parser.on('end', function(name, obj) {
+ console.log('Finished parsing xml!');
+ });
+
+ request.get('http://www.example.com/test.xml').pipe(parser.saxStream)
+
## Module
### xml2object(xmlFile, elements)
-Constructor for creating an instance of the xml parser
+Constructor for creating an instance of the xml parser.
+The xmlFile argument is optional. If not specified you need to pipe your own Stream into the parser.saxStream.
var xml2object = require('xml2object');
// Parse the myAnimals.xml file looking for <animal> elements
var parser = new xml2object('myAnimals.xml', [ 'animal' ]);
+### .saxStream
+
+The underlying saxStream. When not using the xmlFile argument in the constructor this stream can be used as
+a destination for pipe().
+
### .start()
Triggers the xml file to start streaming to the parser. Call this method after you have bound to the events.
@@ -47,6 +75,8 @@ Triggers the xml file to start streaming to the parser. Call this method after y
// Start parsing the XML
parser.start();
+
+
### Event: 'object'
function(name, obj) { ... }
Please sign in to comment.
Something went wrong with that request. Please try again.