Friday, March 16, 2018

UWP Tip #17 - UWP Community Toolkit - Part 14, RSS Parser

Welcome back to my UWP Community Toolkit series. The previous five tips in the series can be found here:

Intro

The toolkit now includes two helper classes for parsing, one for parsing RSS feed data and the other for parsing markdown. These parsers simplify working with each of these formats. Today we will examine the RSS Parser helper.

RSS Parser

The RSS Parser helper consists of two classes. An RssParser which takes RSS feed data and does the parsing into a list of feed items. The RssParser has a parameterless constructor and a single Parse method which takes the feed data as a string and returns an IEnumerable<RssSchema>.

RssSchema is the other class included with the helper and is the representation of a feed item. The RssSchema has a parameterless constructor and the following properties:
  • Author
  • Content
  • ExtraImageUrl
  • FeedUrl
  • ImageUrl
  • MediaUrl
  • PublishDate
  • Summary
  • Title
If you are familiar with RSS data, these properties should all be familiar. Each is a string type except for PublishDate, which is a DateTime.

I created a simple static helper method which takes a string containing feed data returned from an HttpClient call and returns a list of feed items (RssSchema).

public static IList<RssSchema> ParseRssFeed(string feed)
{
     if (string.IsNullOrWhiteSpace(feed))
     {
         throw new ArgumentException("Feed cannot be empty.", nameof(feed));
     }
     var parser = new RssParser();
     var rssItems = parser.Parse(feed).ToList();

     // Loop to illustrate some of the available properties
     foreach (var item in rssItems)
     {
         Debug.WriteLine($"Title: {item.Title}");
         Debug.WriteLine($"Author: {item.Author}");
         Debug.WriteLine($"Summary: {item.Summary}");
     }
     return rssItems;
}

The foreach loop is unnecessary unless you were actively debugging an issues with a particular feed being parsed. The method could end before the loop with:

return parser.Parse(feed).ToList();

Wrap-Up

There isn't much to explain with this helper. It saves you a bit of parsing and provides a class representation of a feed item. While it is a simple helper, the RSS Parser is particularly interesting to me. I am always looking for ways to leverage RSS data to improve the workflow for creating blog posts for my other blog, the Morning Dew. The UWP companion app for that blog is rather basic and sorely in need of a refresh. Helpers like these provide a little extra motivation to go out and make some progress on Morning Dew UWP vNext.

Go check out the source and give the RSS Parser a try today!

Happy coding!

del.icio.us Tags: ,

No comments:

Post a Comment