xml2js read from url

xml2js read from url

本文关键字:url from read xml2js      更新时间:2023-09-26

所以我有NodeJS并安装了模块xml2js。在本教程中,我们有一个示例,从目录中获取一个xml文件,并将其转换为示例中的JSON.stringify()。现在是否有可能不调用本地xml文件(foo.xml),而是调用xml服务的url,例如:www.wunderground.com/city.ect/$data=xml

var parser = new xml2js.Parser(); 
parser.addListener('end', function(result) {
    var res = JSON.stringify(result);   
        console.log('converted'); 
}); 
fs.readFile(__dirname + '/foo.xml', function(err, data) {
    parser.parseString(data); 
});

您需要创建http请求而不是读取文件。我想大概是这样的:

http.get("http://www.google.com/index.html", function(res) {
  res.on('data', function (chunk) {
    parser.parseString(chunk); 
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

http://nodejs.org/api/http.html http_http_request_options_callback