2017-04-09 61 views
1

我在變量名中含有冒號的XML(:) 它看起來是這樣的:問題用解析xml2js

<samlp:Response> 
data 
</samlp:Response> 

我使用下面的代碼到這個XML解析成JSON,但不能使用它,因爲標籤名稱包含冒號。

var xml2js = require('xml2js'); 
var parser = new xml2js.Parser(); 
var fs = require('fs'); 

    fs.readFile(
    filePath, 
    function(err,data){ 
    if(!err){ 
     parser.parseString(data, function (err, result) { 
     //Getting a linter warning/error at this point 
     console.log(result.samlp:Response); 
     }); 
    }else{ 
     callback('error while parsing assertion'+err); 
    } 
    } 
); 

}; 

錯誤:

events.js:161 
     throw er; // Unhandled 'error' event 
    ^

TypeError: Cannot read property 'Response' of undefined 

我怎樣才能成功地解析這個XML不改變我的XML的內容是什麼?

enter image description here

+0

加上'如果(ERR)'回調裏面看到實際的錯誤 –

+0

@MariaInesParnisari請看截圖,parseString是沒有得到所謂的,因爲它是一個syntaxe錯誤。 – nitinsh99

回答

1

xml2js可以讓你明確地通過添加stripPrefix to the tagNameProcessors array in your config options設置XML命名空間去除。

const xml2js = require('xml2js') 
const processors = xml2js.processors 
const xmlParser = xml2js.Parser({ 
    tagNameProcessors: [processors.stripPrefix] 
}) 
const fs = require('fs') 

fs.readFile(filepath, 'utf8', (err, data) => { 
    if (err) { 
    //handle error 
    console.log(err) 
    } else { 
    xmlParser.parseString(data, (err, result) => { 
     if (err) { 
     // handle error  
     console.log(err) 
     } else { 
     console.log(result) 
     } 
    }) 
    } 
})