在编码方面,我真的很生气,并且一直在努力寻找答案,但我现在正处于最后阶段.
我的网站有一个存储的RSS URL数据库.对于我的生活,我无法弄清楚如何循环并显示所有RSS提要数据.
我可以得到一个显示正常的提要,但显示所有这些,我只是不知道该怎么做才能让它们全部展示.任何帮助将不胜感激!
型号:RSS.cs
namespace MyWebsite.Models
{
public class RSS
{
public string Link { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string PubDate { get; set; }
public string Date { get; set; }
}
}
型号:RSSReader.cs
namespace MyWebsite.Models
{
public class RSSReader
{
private static string _URL = "";
public static IEnumerable<RSS> GetRSSFeed()
{
IEnumerable<RSS> feeds = null;
XDocument feedXml = null;
XNamespace rss = "http://purl.org/rss/1.0/";
XNamespace dc = "http://purl.org/dc/elements/1.1/";
int count = 0;
foreach (var url in BansheeData.GetURL(count))
{
_URL = url.url1;
feedXml = XDocument.Load(_URL);
feeds = from feed in feedXml.Descendants(rss + "item")
select new RSS
{
Title = feed.Element(rss + "title").Value,
Link = feed.Element(rss + "link").Value,
Date = feed.Element(dc + "date").Value.Remove(10)
};
count++;
}
return feeds;
}
}
}
控制器:RSSController.cs
public ActionResult Index()
{
var urlFeed = MyWebsite.Models.RSSReader.GetRSSFeed();
return View(urlFeed);
}
查看:_RSSFeed.cshtml
@model IEnumerable<MyWebsite.Models.RSS>
@foreach (var item in Model) {
<section>
<header class="overflow">
<h1>
<a href="@item.Link" target="_blank" class="alt overflow">
<span class="fl">@Html.Raw(item.Title)</span>
<span class="ref fr">Source, @Html.Encode(item.Date)</span>
</a>
</h1>
</header>
</section>
}
最佳答案 我想我的代码中发现了一个问题.您缺少在每次迭代中将项目添加到列表中.
所以代替:
foreach (var url in BansheeData.GetURL(count))
{
_URL = url.url1;
feedXml = XDocument.Load(_URL);
feeds = from feed in feedXml.Descendants(rss + "item")
select new RSS
{
Title = feed.Element(rss + "title").Value,
Link = feed.Element(rss + "link").Value,
Date = feed.Element(dc + "date").Value.Remove(10)
};
count++;
}
return feeds;
您尝试将AddRange添加到每个迭代的列表中:
var rssList = new List<RSS>;
foreach (var url in BansheeData.GetURL(count))
{
_URL = url.url1;
feedXml = XDocument.Load(_URL);
feeds = from feed in feedXml.Descendants(rss + "item")
select new RSS
{
Title = feed.Element(rss + "title").Value,
Link = feed.Element(rss + "link").Value,
Date = feed.Element(dc + "date").Value.Remove(10)
};
rssList.AddRange(feeds);
count++;
}
return rssList;
这应该有所帮助.现在你应该得到RSS的完整列表.核心逻辑是当你迭代并且你在每个迭代周期中得到你需要的项目时你应该记住它们.这意味着将它们保存在临时列表中.