Best Way to read rss feed in .net Using C#

前端 未结 5 1575
小鲜肉
小鲜肉 2020-11-29 16:25

What is the best way to read RSS feeds?

I am using XmlTextReader to achieve this. Is there any other best way to do it?

XmlText         


        
5条回答
  •  误落风尘
    2020-11-29 16:53

    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  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;
        }
    }
    

提交回复
热议问题