2014-01-06 34 views
0

我试图解析通过一个kml文件懒洋洋地与xml流模块和运行到缺乏相关的例子。这是我的代码到目前为止。lazy.js和xml流解析

var fs = require('fs'); 
var path = require('path'); 
var xmlStream = require('xml-stream'); 
var lazy = require('lazy.js') 

var stream = fs.createReadStream('./Sindh.kml'); 

var xml = new xmlStream(stream); 

var onlyEvents = function(e) { 
    if (e && e._events) { 
     return 1; 
    } 
    else { 
     return 0; 
    } 
} 

lazy(xml).filter(onlyEvents).take(20).each(function(e) { 
    console.log(e); 
    console.log('\n'); 
}); 

//xml.preserve('Polygon', true); 
//xml.on('endElement: Polygon', function(poly) { 
// var coordString = poly.outerBoundaryIs.LinearRing.coordinates.$children.join().trim(); 


    //console.log('\n\n'); 
//}) 

所以,这个想法是对的endElement事件过滤从事件发射器输出复制出带有注释的文本的行为。我通过运行代码获得输出,我只是不知道我在看什么或从哪里去。

我是新来的流和lazy.js所以道歉,如果这是一个总noob问题。也许我只是不理解我从循环中得到的物体。

+0

这是一个棘手,因为'XML-stream'库似乎暴露出一些*流,如*,它提供了一个稍微不同的接口到Node中的日常'stream.Readable'。懒惰目前还没有提供一种将任意源作为序列封装的方法。但是,这是我将在不久的将来添加的内容。如果可以的话,我会重新审视这个问题。 –

+0

感谢您的回复。所以我想现在我的选择是编写一个自定义序列来解析xml,就像你在json例子中所做的那样,或者编写一个更加严格遵守流的xml流模块。可读接口。 如果我走后者的路线,我应该期待从懒惰的每个输出像一个on.data事件,是否正确? – ddombrow

回答

2

因此,昨天我发布了Lazy.js的0.3.2版本,其中包括一个名为createWrapper的方法。从文档:

定义自定义StreamLikeSequences的包装。如果 需要一种将事件流作为序列处理的方式,但 不能使用Lazy的现有接口(即,您使用自己的自定义事件从库中包装对象 ),这很有用。

不要指望这种方法在这个确切的形式(或甚至与这个确切的名称)存在无限期;这只是最终可能在Lazy 1.0中产生的初步草图。但是,因为它现在存在,下面是一个示例,说明如何将它用于您的目的,使用Google的KML tutorial中的库(我不知道这是否是您使用的“KML”;但它应该说明这是如何工作如何):

var fs  = require('fs'), 
    XmlStream = require('xml-stream'), 
    Lazy  = require('./lazy.node'); 

// Here we are wrapping an XML stream as defined by xml-stream. We're defining 
// our wrapper so that it takes the stream as the first argument, and the 
// selector to scan for as the second. 
var wrapper = Lazy.createWrapper(function(source, selector) { 
    // Within this wrapper function, 'this' is bound to the sequence being created. 
    var sequence = this; 

    // The xml-stream library emits the event 'endElement:x' when it encounters 
    // an <x> element in the document. 
    source.on('endElement:' + selector, function(node) { 
    // Calling 'emit' makes this data part of the sequence. 
    sequence.emit(node); 
    }); 
}); 

// We can now use the factory we just defined to create a new sequence from an 
// XML stream. 
var stream = fs.createReadStream('KML_Samples.kml'); 
var xml = new XmlStream(stream); 
var sequence = wrapper(xml, 'Placemark'); 

// This sequence can be used just like any other, with all of the same helper 
// methods we know and love. 
sequence.skip(5).take(5).pluck('name').each(function(placemarkName) { 
    console.log(placemarkName); 
}); 

输出:

Tessellated 
Untessellated 
Absolute 
Absolute Extruded 
Relative 
+0

不错!将尽快尝试。我认为这将是一个很好的概念。由于我一直在研究npm模块,所以我一直注意到类似于流的“模式”,特别是解析器。 – ddombrow