我正在使用xml2js,因为我需要将XML feed转换为JSON。但是当我接收到XML时,它显示预期的Æ、Ø和Å。但在解析后,我收到的是:Ø作为\ufffd或�。我已经将编码设置为UTF-8,所以我不确定我做错了什么。有谁能给我指点一下呢?
var fs = require('fs')
var https = require('https')
var xml2js = require('xml2js')
var parser = new xml2js.Parser()
router.get('/api/xml', (req, res) => {
https.get('urlForRequest', function (response) {
var response_data = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
response_data += chunk;
});
response.on('end', function () {
parser.parseString(response_data, function (err, result) {
if (err) {
console.log('Got error: ' + err.message);
} else {
res.json(result)
}
});
});
res.on('error', function (err) {
console.log('Got error: ' + err.message);
})
})
})
更新:
我尝试按照你的步骤操作。如果我将XML文件获取并存储在本地的.xml文件中,一切都很好。但是,如果我从我的来源获取(完全相同的GET请求),那么就无法工作。
curl响应http://localhost:9090/products.xml -v > download.xml
Connected to localhost (::1) port 9090 (#0)
GET /products.xml HTTP/1.1
Host: localhost:9090
User-Agent: curl/7.54.0
Accept: */*
HTTP/1.1 200 OK
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Thu, 07 Jun 2018 09:56:41 GMT
ETag: W/"9471b6-163d9ad4696"
Content-Type: text/xml; charset=UTF-8
Content-Length: 9728438
Date: Thu, 07 Jun 2018 10:00:09 GMT
Connection: keep-alive
响应 curl 请求的“真实”来源(如果有关系,这是一个 HTTPS 请求)
User-Agent: curl/7.54.0
Accept: */*
HTTP/1.1 200 OK
Date: Thu, 07 Jun 2018 10:10:29 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/5.4.16
X-Powered-By: PHP/5.4.16
Vary: Accept-Encoding
Connection: close
Transfer-Encoding: chunked
Content-Type: text/xml; charset=iso-8859-1