在我的应用程序中,我将保存用户保存的动态RSS订阅源URL。所以我想知道如何读取rss feed返回的xml。那个xml的结构是什么?我查看了一些Feed网址,我注意到他们中的大多数都有title
和description
标签,但我不确定这一点。如果我得到这两个标签,那么我将解析xml,但如果它们并不总是可用,那么在这种情况下如何解析xml。
这两个包含标题和描述标签
http://rss.news.yahoo.com/rss/entertainment
http://xml.weather.yahoo.com/forecastrss?p=USCA1116
答案 0 :(得分:0)
首先,您需要阅读XML文件,我建议您使用XPath或Linq to XML,正如您已经说过的,构成Feed的主要元素有三个; “标题”,“链接”和“描述”。
不久前我写了一个代码来做到这一点,我希望这适合你。
我创建了这两个实体。
public class RssFeed
{
public string Title { get; set; }
public string Link { get; set; }
public string Description { get; set; }
public string PubDate { get; set; }
public string Language { get; set; }
public ObservableCollection<RssItem> RssItems { get; set; }
}
public class RssItem
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
}
然后在这个方法中,我使用Linq to XML
从XML文件中读取每个元素private static void ReadFeeds()
{
string uri = @"http://news.yahoo.com/rss/entertainment";
WebClient client = new WebClient();
client.DownloadStringAsync(new Uri(uri, UriKind.Absolute));
client.DownloadStringCompleted += (s, a) =>
{
if (a.Error == null && !a.Cancelled)
{
var rssReader = XDocument.Parse(a.Result);
var feed = (from rssFeed in rssReader.Descendants("channel")
select new RssFeed()
{
Title = null != rssFeed.Descendants("title").FirstOrDefault() ?
rssFeed.Descendants("title").First().Value : string.Empty,
Link = null != rssFeed.Descendants("link").FirstOrDefault() ?
rssFeed.Descendants("link").First().Value : string.Empty,
Description = null != rssFeed.Descendants("description").FirstOrDefault() ?
rssFeed.Descendants("description").First().Value : string.Empty,
PubDate = null != rssFeed.Descendants("pubDate").FirstOrDefault() ?
rssFeed.Descendants("pubDate").First().Value : string.Empty,
Language = null != rssFeed.Descendants("language").FirstOrDefault() ?
rssFeed.Descendants("language").First().Value : string.Empty
}).Single();
var rssFeeds = (from rssItems in rssReader.Descendants("item")
select new RssItem()
{
Title = null != rssItems.Descendants("title").FirstOrDefault() ?
rssItems.Descendants("title").First().Value : string.Empty,
Link = null != rssItems.Descendants("link").FirstOrDefault() ?
rssItems.Descendants("link").First().Value : string.Empty,
Description = null != rssItems.Descendants("description").FirstOrDefault() ?
rssItems.Descendants("description").First().Value : string.Empty,
}).ToList();
feed.RssItems = new ObservableCollection<RssItem>(rssFeeds);
}
};
}
最后,您可以在任何地方显示您的Feed。