【问题标题】:How to parse xml to Json ionic 2如何将 xml 解析为 Json ionic 2
【发布时间】:2017-03-23 15:59:59
【问题描述】:

过去三天我一直在处理这个问题。我想将通过 HTTP 检索的 XML 转换为 JSON,以便我可以在 ionic 2 中显示它。这是我在提供程序中的代码。任何帮助将不胜感激。谢谢!

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import 'rxjs/add/operator/map';

import * as xml2js from "xml2js";


@Injectable()
export class News {

    constructor(public http: Http) { }

    public getData() {

        this
            .http
            .get('https://www.ug.edu.gh/news.xml')
            .map(res => {

                var cleanedString = res.toString().replace("\ufeff", "");

                xml2js
                .parseString(cleanedString, (error, result) => {

                    console.log(result);
                    return result;

                });

            })
            .subscribe((data) => {
                console.log(data)
            }, (err) => {
                console.log(err)
            });

    }
}

【问题讨论】:

    标签: json xml angular ionic2


    【解决方案1】:

    用于在 ionic 2 中将 xml 解析为 json 您现在可以使用命令安装 xml2json 的类型

    typings install xml2json --save
    

    如果它产生这样的错误

    'typings' is not recognized as an internal or external command,
     operable program or batch file.
    

    然后先用这个命令安装打字

    npm install typings -g
    

    然后运行上一个命令

    typings install xml2json --save
    

    然后它会正常工作。 希望对你有用

    【讨论】:

      【解决方案2】:

      你快到了。当你 return 来自 parseString 方法的数据时,事情就出错了。您只需要使用一个临时变量,从 parseString 方法分配结果并返回该临时变量,如下所示:

      // ...
      .map(res => {
      
          let cleanedString = res.toString().replace("\ufeff", "");
          let jsonData;
      
          xml2js
          .parseString(cleanedString, (error, result) => {
      
              if(error) {
                  console.error(error);
                  jsonData = error;
              } else {
                  jsonData = result;
              }
      
          });
      
          return jsonData;
      
      }).subscribe((data) => {
      // ...
      

      更深入的描述和替代方法here.

      【讨论】:

        猜你喜欢
        • 2018-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-08
        • 1970-01-01
        • 2023-03-24
        • 2021-10-31
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多