希望有人可以提供帮助。我一直绞尽脑汁想要解决这个问题。
我正在尝试使用angular和x2js解析xml rss文件,只返回 item 对象。它的格式如下:
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
<channel>
<title>Test Title</title>
<link>
https:somelocation.com
</link>
<description>List Title 1</description>
<pubDate>Wed, 26 Apr 2017 13:04:51 GMT</pubDate>
<dc:date>2017-04-26T13:04:51Z</dc:date>
<item>
<title>Test Title 1</title>
<link>
https://plnkr.co
</link>
<description>
<DIV> <P>Some description text</P> </DIV>
</description>
<pubDate>Wed, 26 Apr 2017 13:04:51 GMT</pubDate>
<guid>
https://plnkr.co
</guid>
<dc:date>2017-04-26T13:04:51Z</dc:date>
</item>
</channel>
</rss>
我可以返回结果,但是当我尝试在我的标记中重复重复时,它会迭代通道中的所有内容,导致空列表对象出现在结果中。这是我的HTML:
<html ng-app="myApp">
<head>
<script data-require="angular.js@4.0.0" data-semver="4.0.0"
src="https://code.angularjs.org/latest/angular.min.js"></script>
<script src="xml2Json.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="listController">
<ul ng-repeat="item in list">
<li ng-repeat="i in item">
<h2><a href="{{i.link}}">{{i.title}}</a></h2>
</li>
</ul>
</body>
</html>
以下是我的剧本:
var myApp = angular.module('myApp', []);
myApp.controller('listController', function($scope,$http){
$http.get('rssFeed.xml', {
transformResponse: function (data) {
var x2js = new X2JS();
var listData = x2js.xml_str2json(data);
return listData.rss.channel.item;
}
}).then(function successCallback(response, status){
$scope.list = response;
}, function errorCallback(response, status){
console.log('Request failed' + status);
});
});
plunkr位于:plunker
答案 0 :(得分:0)
我忘了回来关闭它。回答如果它对其他遇到此问题的人有帮助。
我通过从ul标签中删除“ng-repeat”属性更新了我的html,并用它替换了li ng-repeat。我还通过将$scope.list = response;
更改为$scope.list = response.data;
来更新脚本。通过这样做,我能够避免迭代rss中channel标签下的所有内容,并且只针对项目本身。请参阅下面的代码,此处是更新的plunkr。
<html ng-app="myApp">
<head>
<script data-require="angular.js@4.0.0" data-semver="4.0.0"
src="https://code.angularjs.org/latest/angular.min.js"></script>
<script src="xml2Json.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="listController">
<ul>
<li ng-repeat="item in list">
<h2><a href="{{i.link}}">{{i.title}}</a></h2>
</li>
</ul>
</body>
</html>
这是我更新的脚本
var myApp = angular.module('myApp', []);
myApp.controller('listController', function($scope,$http){
$http.get('rssFeed.xml', {
transformResponse: function (data) {
var x2js = new X2JS();
var listData = x2js.xml_str2json(data);
return listData.rss.channel.item;
}
}).then(function successCallback(response, status){
$scope.list = response.data;
}, function errorCallback(response, status){
console.log('Request failed' + status);
});
});