Skip to content

Instantly share code, notes, and snippets.

@jbe2277
Last active May 27, 2019 19:55
Show Gist options
  • Save jbe2277/aba5d70db85923f67c5de88b9583afe9 to your computer and use it in GitHub Desktop.
Save jbe2277/aba5d70db85923f67c5de88b9583afe9 to your computer and use it in GitHub Desktop.
Simple Atom feed reader implementation
internal class SyndicationClient : ISyndicationClient
{
private const string XmlnsAtom2005 = "http://www.w3.org/2005/Atom";
public async Task<FeedDto> RetrieveFeedAsync(Uri uri)
{
XDocument doc;
using (var client = new HttpClient())
using (var stream = await client.GetStreamAsync(uri).ConfigureAwait(false))
{
doc = XDocument.Load(stream);
}
var root = doc.Root;
if (root.Name.NamespaceName == XmlnsAtom2005)
{
var titleName = XName.Get("title", XmlnsAtom2005);
var entryName = XName.Get("entry", XmlnsAtom2005);
var linkName = XName.Get("link", XmlnsAtom2005);
var publishedName = XName.Get("published", XmlnsAtom2005);
var updatedName = XName.Get("updated", XmlnsAtom2005);
var summaryName = XName.Get("summary", XmlnsAtom2005);
return new FeedDto(RemoveHtmlTags(root.Element(titleName).Value), root.Elements().Where(x => x.Name == XName.Get("entry", XmlnsAtom2005))
.Select(x => {
var date = DateTimeOffset.Parse(x.Element(publishedName).Value, CultureInfo.InvariantCulture);
if (date <= new DateTime(1601, 1, 2)) date = DateTimeOffset.Parse(x.Element(updatedName).Value, CultureInfo.InvariantCulture);
return new FeedItemDto(new Uri(x.Element(linkName).Attribute("href").Value),
date,
RemoveHtmlTags(x.Element(titleName).Value),
RemoveHtmlTags(x.Element(summaryName).Value));
}).ToArray());
}
throw new NotSupportedException(root.Name.NamespaceName);
}
private static string RemoveHtmlTags(string message)
{
if (string.IsNullOrEmpty(message)) { return message; }
message = WebUtility.HtmlDecode(message);
return Regex.Replace(Regex.Replace(message, "\\&.{0,4}\\;", ""), "<.*?>", "");
}
}
public sealed class FeedDto
{
public FeedDto(string title, IReadOnlyList<FeedItemDto> items)
{
Title = title;
Items = items;
}
public string Title { get; }
public IReadOnlyList<FeedItemDto> Items { get; }
}
public sealed class FeedItemDto
{
public FeedItemDto(Uri uri, DateTimeOffset date, string name, string description)
{
Uri = uri;
Date = date;
Name = name;
Description = description;
}
public Uri Uri { get; }
public DateTimeOffset Date { get; }
public string Name { get; }
public string Description { get; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment