How overwrite in node/xmldom errorHandler on DOMParser?

半城伤御伤魂 提交于 2019-12-11 06:27:57

问题


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.

Documentation say:

//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:


This is the runable code:

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


来源:https://stackoverflow.com/questions/43040982/how-overwrite-in-node-xmldom-errorhandler-on-domparser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!