【问题标题】:convert xml to json after retrieving records from db using angularjs使用 angularjs 从 db 检索记录后将 xml 转换为 json
【发布时间】:2016-12-05 12:21:14
【问题描述】:

我必须将xml response to json 转换为angularjs。我正在使用一个以 xml 格式提供响应的 Rest api,但 angularjs 在通过 $http.get() 检索时需要 json 响应。

以下是我如何在 angularjs 中使用 rest api。

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {

$http({
 method: 'GET',
 url: "https://some-url?fieldList=field1,field2"
}).then(function(response) {
        $scope.obj=response.data.records;},function(response){});}
});
</scripts>

如何将 xml 响应转换为 json 并将其作为输入提供给某个变量 $scope.obj?

【问题讨论】:

    标签: javascript angularjs json xml


    【解决方案1】:

    以下是实现这一目标的方法, 我使用了这个页面上给出的函数https://davidwalsh.name/convert-xml-json

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
     };
    xhttp.open("GET", "your.xml", true);
    xhttp.send();
    
    function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    document.getElementById("demo").innerHTML =
    xmlToJson(xmlDoc);
    }
    function xmlToJson(xml) {
    
    // Create the return object
    var obj = {};
    
    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { // text
        obj = xml.nodeValue;
    }
    
    // do children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 2010-10-04
      • 2014-01-06
      • 2015-09-02
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多