使用angularjs从数据库检索记录后,将xml转换为json

使用angularjs从数据库检索记录后,将xml转换为json

问题描述:

我必须将xml response to json转换为angularjs。我使用的是一个Rest api,它以xml格式提供响应,但是当通过$ http.get()获取时,angularjs需要json响应。使用angularjs从数据库检索记录后,将xml转换为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?

这里是你如何能做到这一点, 我用这个页面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; 
}; 
上给出的函数