在AngularJS中将XML url转换为JSON url

时间:2015-06-17 05:22:47

标签: javascript json xml angularjs

有没有办法将XML网址转换为JSON网址,以便我可以在我的网站上使用它?

{"breakfast_menu": {
"food": [
  {
    "name": "Belgian Waffles",
    "price": "$5.95",
    "description": "Two of our famous Belgian Waffles with plenty of real maple syrup",
    "calories": "650"
  },
  {
    "name": "Strawberry Belgian Waffles",
    "price": "$7.95",
    "description": "Light Belgian waffles covered with strawberries and whipped cream",
    "calories": "900"
  },
  {
    "name": "Berry-Berry Belgian Waffles",
    "price": "$8.95",
    "description": "Light Belgian waffles covered with an assortment of fresh berries and whipped cream",
    "calories": "900"
  },
  {
    "name": "French Toast",
    "price": "$4.50",
    "description": "Thick slices made from our homemade sourdough bread",
    "calories": "600"
  },
  {
    "name": "Homestyle Breakfast",
    "price": "$6.95",
    "description": "Two eggs, bacon or sausage, toast, and our ever-popular hash browns",
    "calories": "950"
  }
]}}

假设URL为http://www.w3schools.com/xml/simple.xml,那我该如何将其转换为JSON,以便我可以在AngularJS中使用它

2 个答案:

答案 0 :(得分:1)

您可以使用xml2json.js将XML转换为JSON

请务必阅读accompanying article on the xml.com,其中详细介绍了这些转化的有趣问题。

<强>用法:

  $scope.xml = '<breakfast_menu>'+
                '<food>'+
                   '<name>Belgian Waffles</name>'+
                   '<price>$5.95</price>'+
                '</food>'+
              '</breakfast_menu>';

  var dom = parseXml($scope.xml);
  $scope.json = xml2json(dom,"  ");

使用{{json}}在视图中显示json!

{ "breakfast_menu":{"food":{ "name":"Belgian Waffles", "price":"$5.95" }} }

这是一个有效的plunkr

答案 1 :(得分:-1)

@SFDC:嗨......这个xml链接(&#39; http://www.webservicex.com/globalweather.asmx/GetCitiesByCountry&#39;)可以从xml转换为json格式