【问题标题】:Loading some XML into JSON in NodeJS在 NodeJS 中将一些 XML 加载到 JSON 中
【发布时间】:2018-04-16 20:55:02
【问题描述】:

我是 NodeJS 的新手,并试图弄清楚如何从 REST 服务加载一些 xml 数据并将其转换为 JSON,以便之后将其加载到我的视图中。

我正在尝试使用Hapi API 进行查询并将其加载到 xml 解析器中,然后将其转换为 JSON

执行以下操作似乎正确加载了 xml 对象,并且在打印时它实际上向我显示了一些 JSON。 是否意味着我不再需要转换为 JSON 了?

const server = new Hapi.Server();
...
server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        Request.get('http://ws.seloger.com/search.xml?&idtt=2&idtypebien=2,1&ci=750056&pxmax=400000&tri=initial&naturebien=1,2&surfacemin=65search.xml?',
            function (error, response, body) {
            if (error) {
                throw error;
            }

            var parse = require('xml-parser');
            var inspect = require('util').inspect;    
            var obj = parse(body);
            console.log(inspect(obj, { colors: true, depth: 4 }));

请注意,显示的 JSON 也不是我想要的,即。使用attributeschildren 等显示详细信息:

{ declaration: { attributes: { version: '1.0', encoding: 'UTF-8' } },
root: 
{ name: 'recherche',
    attributes: {},
    children: 
    [ { name: 'resume',
        attributes: {},
        children: [],
        content: '....' },

但是寻找更像this 的东西(可能只是不同的表示)

【问题讨论】:

    标签: json node.js xml converter


    【解决方案1】:

    所以我发现我的问题似乎与解析器本身有关。使用这个我得到了我需要的东西:

    var parseString = require('xml2js').parseString;
    parseString(body, function (err, jsonData) {
        reply.view('index', { result: body });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      相关资源
      最近更新 更多