2017-03-27 59 views
0

我使用https://github.com/jindw/xmldom並希望檢查XML文件的解析器。 該文檔寫道它必須覆蓋DOMParser構造函數上的locator + errorHandler。如何覆蓋DOMParser上的node/xmldom 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)} 
}) 

回答

0

這是可運行的代碼:

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