gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:16:07 24 4
gpt4 key购买 nike

我必须在 angularjs 中将 xml 响应转换为 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;
};

关于javascript - 使用 angularjs 从数据库检索记录后将 xml 转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40974186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com