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

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

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

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

sax

sax的使用方式以下:编程

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

fs.writeFileSync('file.xml','<xml>Hello, <who name="world">world</who>!</xml>');

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文档。ui

参考资料

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

相关文章
相关标签/搜索