C# parse XML/RSS

Date: 2020-10-14

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DatasourceAdapter
{
    public class DatasourceRepository
    {
        public async Task<IEnumerable<NewsItem>> GetRssFeed(string url)
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetAsync(url);
            using (var content = await response.Content.ReadAsStreamAsync())
            {
                var doc = XDocument.Load(content);
                var items = doc.Descendants(XName.Get("item"));
                
                return items.Select(x => {

                    var title = x.Descendants().FirstOrDefault(e => e.Name == "title")?.Value;
                    var description = x.Descendants().FirstOrDefault(e => e.Name == "description")?.Value;
                    var link = x.Descendants().FirstOrDefault(e => e.Name == "link")?.Value;
                    DateTime.TryParse( x.Descendants().FirstOrDefault(e => e.Name == "pubdate")?.Value, out var date);
                    var image = x.Descendants().Where(e => e.Name == "enclosure")
                            .Where(e => e.Attributes(XName.Get("type")).Any(a => a.Value.IndexOf("image") >= 0))
                            .Select(e => e.Attributes(XName.Get("url")).Select(a => a.Value).FirstOrDefault())
                            .FirstOrDefault();

                    var categories = x.Descendants().Where(e => e.Name == "category").Select(e => e.Value).ToList();

                    return new NewsItem() {
                        Title = title,
                        Description = description,
                        Link = link,
                        Date = date,
                        Image = image,
                        Categories = categories
                    };
                }).ToList();
            }
        }
        
    }
}
41460cookie-checkC# parse XML/RSS