在我的应用程序中,我将拥有用户保存的动态RSS feed URL。因此,我想知道如何阅读RSS Feed将返回的XML。该XML的结构是什么?我已经回顾了一些供稿URL,我注意到其中大多数都有title
和description
标签,但我不确定。如果我得到这两个标签,那么我将解析XML,但是如果它们并不总是可用,那么在这种情况下如何解析XML。
这两个包含标题和描述标签
http://rss.news.yahoo.com/rss/entertainment
http://xml.weather.yahoo.com/forecastrss?p=USCA1116
首先,您需要阅读XML文件,为此我建议您将XPATH或LINQ用于XML,正如您已经说过的,有三个主要元素可以构成feed;"标题","链接"one_answers"描述"。
不久前我写了一个代码来做到这一点,我希望这对您有用。
我创建了这两个实体。
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到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);
}
};
}
最后,您有任何想要的供稿。