我使用https://github.com/jindw/xmldom并希望检查XML文件上的parseerrors。
该文档写道,有必要在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)}
})

最佳答案

这是可运行的代码:

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

关于node.js - 如何在DOMParser的node/xmldom errorHandler中覆盖?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43040982/

10-14 17:17