【问题标题】:Convert XML url to JSON url in AngularJS在 AngularJS 中将 XML url 转换为 JSON url
【发布时间】:2015-09-02 04:12:37
【问题描述】:

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

{"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 中使用它

【问题讨论】:

    标签: javascript json xml angularjs


    【解决方案1】:

    @SFDC:Hi...这个xml链接('http://www.webservicex.com/globalweather.asmx/GetCitiesByCountry')可以从xml转换成json格式

    【讨论】:

      【解决方案2】:

      您可以使用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

      【讨论】:

      • 在 $scope.xml 中我可以访问 url 而不是数据
      • 当然,您只需要使用$http 服务并获取xml
      • 抱歉之前的评论是 plunker Plunker
      • @RamanaUday:嗨..我检查了你的 plunker..发现以下问题。 - 首先,查看此错误的控制台请求的资源上不存在“Access-Control-Allow-Origin”标头。这是一个 CORS 问题。其次..你正在尝试做$scope.xml = $http.get('...')$http.get 服务返回一个 promise 而不是响应数据本身。所以你不能直接把它赋值给一个变量。
      • 这是更新后的plunkr。我已将 url 从 w3schools.com/xml/simple.xml 更改为 cdn.rawgit.com/motyar/bcf1d2b36e8777fd77d6/raw/… 以使其正常工作。关于 CORS 问题..参见this。希望它有所帮助:)
      猜你喜欢
      • 1970-01-01
      • 2015-08-07
      • 2016-11-02
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 2023-04-06
      • 2015-09-16
      相关资源
      最近更新 更多