如何在DOMParser上的node / xmldom errorHandler中覆盖?

时间:2017-03-27 08:06:07

标签: node.js xmldom

我使用https://github.com/jindw/xmldom并希望检查XML文件的解析错误。 文档写道,有必要在DOMParser的构造函数上覆盖locator + errorHandler。

但我找不到任何代码示例,如何在节点上下文中使用它们。

文件说:

//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)}
})

1 个答案:

答案 0 :(得分:2)

这是可运行的代码:

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 );