本文介绍了如何在DOMParser的node/xmldom errorHandler中覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 https://github.com/jindw/xmldom 并希望检查XML上的parseerrors文件.该文档写道,有必要在DOMParser的构造函数上覆盖locator + errorHandler.
I use https://github.com/jindw/xmldom and want check parseerrors on XML files.The documentation write it's necessary to overwrite locator + errorHandler on constructor of DOMParser.
但是我找不到任何代码示例,以及如何在节点上下文中使用它们.
But I can't find anywhere code example, how to use these in node context.
文档说明:
//errorHandler is supported
new DOMParser({
/**
* locator is always need for error position info
*/
locator:{},
/**
* you can override the errorHandler for xml parser
* @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
*/
errorHandler:{warning:function(w){console.warn(w)},error:callback,fatalError:callback}
//only callback model
//errorHandler:function(level,msg){console.log(level,msg)}
})
推荐答案
这是可运行的代码:
var DOMParser = require('xmldom').DOMParser;
let mylocator = {};
let parseLog = {errorLevel: 0};
let parser = new DOMParser({
locator: mylocator,
errorHandler: {
warning: (msg) => {manageXmlParseError(msg,1,parseLog)},
error: (msg) => {manageXmlParseError(msg,2,parseLog)},
fatalError: (msg) => {manageXmlParseError(msg,3,parseLog)},
},
});
function manageXmlParseError(msg,errorLevel,errorLog){
if( (errorLog.errorLevel == null) || (errorLog.errorLevel < errorLevel)){
errorLog.errorLevel = errorLevel;
}
if(errorLog[errorLevel.toString()] == null){
errorLog[errorLevel.toString()] = [];
}
errorLog[errorLevel.toString()].push(msg);
}
var doc = parser.parseFromString(
'<xml xmlns="a" xmlns:c="./lite">\n'+
'\t<child>test</child>\n'+
'\t<child22><<</child>\n'+
'\t<child/>\n'+
'</xml>'
,'text/xml');
console.info("parsestatus ==> " + parseLog.errorLevel + "\nlocator:" + mylocator.columnNumber + "/" + mylocator.lineNumber );
这篇关于如何在DOMParser的node/xmldom errorHandler中覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!