[英]convert xml to json after retrieving records from db using angularjs
我必須在angularjs
xml response to json
轉換xml response to json
。 我使用Rest api以xml格式提供響應,但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?
以下是如何實現這一點,我使用了本頁面給出的功能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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.