使用 C # 在.net 中读取 rss feed 的最佳方法

阅读 RSS 频道的最佳方法是什么?

我正在使用 XmlTextReader来实现这一点。有没有其他最好的方法来做到这一点?

XmlTextReader reader = new XmlTextReader(strURL);


DataSet ds = new DataSet();
ds.ReadXml(reader);

在使用 XmlTextReader读取 RSS 订阅之后,有没有什么方法可以将数据填充到 ListItem而不是 DataSet

enter image description here

149426 次浏览

You're looking for the SyndicationFeed class, which does exactly that.

Add System.ServiceModel in references

Using SyndicationFeed:

string url = "http://fooblog.com/feed";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
foreach (SyndicationItem item in feed.Items)
{
String subject = item.Title.Text;
String summary = item.Summary.Text;
...
}

Use this :

private string GetAlbumRSS(SyndicationItem album)
{


string url = "";
foreach (SyndicationElementExtension ext in album.ElementExtensions)
if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
return (url);


}
protected void Page_Load(object sender, EventArgs e)
{
string albumRSS;
string url = "http://www.SomeSite.com/rss‎";
XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);
r.Close();
foreach (SyndicationItem album in albums.Items)
{


cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
albumRSS = GetAlbumRSS(album);


}






}

This is an old post, but to save people some time if you get here now like I did, I suggest you have a look at the CodeHollow.FeedReader package which supports a wider range of RSS versions, is easier to use and seems more robust. https://github.com/codehollow/FeedReader

Update: This supports only with UWP - Windows Community Toolkit

There is a much easier way now. You can use the RssParser class. The sample code is given below.

public async void ParseRSS()
{
string feed = null;


using (var client = new HttpClient())
{
try
{
feed = await client.GetStringAsync("https://visualstudiomagazine.com/rss-feeds/news.aspx");
}
catch { }
}


if (feed != null)
{
var parser = new RssParser();
var rss = parser.Parse(feed);


foreach (var element in rss)
{
Console.WriteLine($"Title: {element.Title}");
Console.WriteLine($"Summary: {element.Summary}");
}
}
}

For non-UWP use the Syndication from the namespace System.ServiceModel.Syndication as others suggested.

public static IEnumerable <FeedItem> GetLatestFivePosts() {
var reader = XmlReader.Create("https://sibeeshpassion.com/feed/");
var feed = SyndicationFeed.Load(reader);
reader.Close();
return (from itm in feed.Items select new FeedItem {
Title = itm.Title.Text, Link = itm.Id
}).ToList().Take(5);
}


public class FeedItem {
public string Title {
get;
set;
}
public string Link {
get;
set;
}
}