javascript - 将 XML 解析为 JSON UTF-8

标签 javascript json node.js express xml2js

我正在使用 xml2js,因为我需要将 XML 提要转换为 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 > 下载.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

最佳答案

我已经设置了一些脚本文件来复制您的结果。.据我所知,一切似乎都正常。

我已经创建了一个快速服务器来为其中包含 ÅØ 字符的静态 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 > 下载.xml

我会检查返回的 header ,我得到了

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

对于我的设置。

关于javascript - 将 XML 解析为 JSON UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50736919/

相关文章:

javascript - 从 Gmail 线程中收集唯一的电子邮件地址

MySQL JSON : finding value of sibling element in sub-array

php - Redis与Sentinel通信

node.js - 直接从 URL 查询字符串提供的 mongo 查询有多危险?

javascript - Discord.js 列出我所有的机器人命令

javascript - 如何将文件路径转换为 ​​blob 对象?

javascript - 如何在jquery中检测F5刷新按键事件?

javascript - 微数据的 tinymce extended_valid_elements

javascript - Angular js : fitlering json properties to be send in a request

java - android studio json数据解析错误