2015-06-17 56 views
2

有沒有辦法將XML url轉換爲JSON url,以便我可以在我的網站中使用它?在AngularJS中將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

回答

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

+0

在$ scope.xml我可以訪問url,而不是數據 –

+0

ofcourse,你只需要使用'$ http'服務並獲取'xml' – nalinc

+0

對不起,以前的評論是plunker [Plunker](http://plnkr.co/edit/q8jdsQLrBlNvECWEmDTz? p =預覽) –