NPM酷库052:sax,按流解析XML

NPM酷库,每天两分钟,了解一个流行NPM库。·

在NPM酷库051中,我们学习了如何使用xml2js库将XML格式文档字符串解析为JavaScript的对象数据,本期,我们继续学习sax,一个可以以流编程的方式解析XML。

使用流编程的方式,并没有直接将XML解析为JSON便捷,但是可以节省内存开销,同时在某些应用领域只能使用流的方式,比如远程XML事件流接口等情况。

sax

sax的使用方式如下:

const fs = require('fs');
const sax = require('sax');

fs.writeFileSync('file.xml','Hello, world!');

let saxStream = sax.createStream();

saxStream.on('opentag', function (node) {
    console.log('opentag',node);
});

fs.createReadStream('file.xml')
  .pipe(saxStream)
  .pipe(fs.createWriteStream('file-copy.xml'));

sax的流对象不但支持data等事件以及pipe 管道,另外还提供了 opentagtextdoctypeopentagstartclosetagattributecommentopencdatacdataclosecdataopennamespaceclosenamespace等事件。

sax除了可以解析XML之外,也可以用来解析HTML文档。

参考资料

https://github.com/isaacs/sax-js

你可能感兴趣的:(javascript,node.js,npm,saxparser,xml)