官网:https://www.npmjs.com/package/sax
github:https://github.com/isaacs/sax-js
此种方式可以非常方便的获取行号信息,很容易对XML定位出错,对于前端XML编辑器,对XML数据进行校验,定位到出错行非常方便。
使用方法:
Usage
var sax = require("./lib/sax"),
strict = true, // set to false for html-mode
parser = sax.parser(strict);
parser.onerror = function (e) {
// an error happened.
};
parser.ontext = function (t) {
// got some text. t is the string of text.
};
parser.onopentag = function (node) {
// opened a tag. node has "name" and "attributes"
};
parser.onattribute = function (attr) {
// an attribute. attr has "name" and "value"
};
parser.onend = function () {
// parser stream is done, and ready to have more stuff written to it.
};
parser.write('<xml>Hello, <who name="world">world</who>!</xml>').close();
// stream usage
// takes the same options as the parser
var saxStream = require("sax").createStream(strict, options)
saxStream.on("error", function (e) {
// unhandled errors will throw, since this is a proper node
// event emitter.
console.error("error!", e)
// clear the error
this._parser.error = null
this._parser.resume()
})
saxStream.on("opentag", function (node) {
// same object as above
})
// pipe is supported, and it's readable/writable
// same chunks coming in also go out.
fs.createReadStream("file.xml")
.pipe(saxStream)
.pipe(fs.createWriteStream("file-copy.xml"))
本文介绍了一种使用SAX解析XML的方法,通过Node.js的sax模块,开发者能够轻松地处理XML文件,包括错误处理、文本获取及标签事件监听等。适用于前端XML编辑器中的数据验证和错误定位。
2

被折叠的 条评论
为什么被折叠?



