将XML解析为JSON UTF-8

3
我正在使用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
2个回答

1
我已经设置了一些脚本文件来复制您的结果...从我看到的情况来看,一切似乎都可以正常工作。
我创建了一个express服务器来提供一个包含ÅØ字符的静态XML文件。这通常是解决这些问题的好方法,隔离问题。

server.js

const express = require("express");
const app = express();
const port = 3000;

app.use('/', express.static(__dirname));
app.listen(port);

console.log('Express started on port ' + port + '...');

index.js

const xml2js = require('xml2js')
const parser = new xml2js.Parser()
const http = require('http');

var url = 'http://localhost:3000/test.xml';

http.get(url, (response) => {

    var response_data = '';     
    // Try latin1 encoding.
    response.setEncoding('latin1');
    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 {
          console.log('Result JSON: ', JSON.stringify(result, null, 4));
        }
      });
    });

});

test.xml

<root>
    <testÅØ id="198787">
    </testÅØ>
</root>

所有文件都在同一个目录中。先启动 server.js,然后再启动 index.js,这将下载测试 XML 文件并显示解析结果。使用我的设置,我得到以下输出:
{
    "root": {
        "testÅØ": [
            {
                "$": {
                    "id": "198787"
                }
            }
        ]
    }
}

我想知道原始的XML文件是否存在问题。我会尝试使用curl下载数据并查看文件的内容,例如:

curl urlForRequest -v > download.xml

我会检查返回的头部信息,我正在获取:

curl http://localhost:3000/test.xml -v > download.xml

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:10:31 GMT
ETag: W/"34-163d982ff58"
Content-Type: text/xml; charset=UTF-8
Content-Length: 52
Date: Thu, 07 Jun 2018 09:52:46 GMT
Connection: keep-alive

对于我的设置。

我能看到真实文件的编码是 ISO-8859-1,我打赌这就是问题所在! - Terry Lennox
1
有什么建议,如何修复它? - Grumme
也许可以尝试这个:response.setEncoding("latin1"); 我会更新我的答案。文件的编码不是UTF-8,所以我们应该尝试其他方法! - Terry Lennox
太好了!服务器应该真正使用utf8,但这是一个很好的解决方法! - Terry Lennox

0

对我有帮助的是在readAsText函数中使用utf-8

reader.readAsText(file, 'utf-8');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接