Wednesday, March 28, 2012

Atom feeds using .NET's built in functionality

We can create RSS 2.0 and Atom 1.0 feeds in .NET using the Syndication feed class as shown below. In this example we will generate Atom 1.0 feeds (you could also do some minor tweaks to this code and generate RSS 2.0 feeds).

For clarification, we will create a feed called “News” containing a single item called “Article1”.



public XmlElement TestFeed()
{
var feed = new SyndicationFeed();
       feed.Title = new TextSyndicationContent("News");
       feed.Id = "123";   
feed.LastUpdatedTime = DateTime.Now;

       SyndicationItem item = new SyndicationItem();
       item.Id = "1";
       item.Title = new TextSyndicationContent("Article1");
       item.LastUpdatedTime = DateTime.Now;

       item.Authors.Add(new SyndicationPerson(null, "Author-Name", null));
       item.Content = new TextSyndicationContent("The entire article comes here");
       item.Links.Add(new SyndicationLink(new Uri("http://www.news.com/etc")));
        
       List<SyndicationItem> items = new List<SyndicationItem>();
       items.Add(item);

       feed.Items = items;

       XmlDocument document = new XmlDocument();
       XmlWriter writer = document.CreateNavigator().AppendChild();
       Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(feed);
       atomFormatter.WriteTo(writer);
       writer.Close();

       return document.DocumentElement;        
}

According to Atom 1.0 feeds standard, the only compulsory fields in an item (“Article1” in this case) are “id”, “title”, and “updated”, the rest are optional. They have been added just to clear some ambiguities regarding the addition of url and author name in a syndication class. 

For more information about Atom 1.0 feeds standard you could visit this page.

No comments:

Post a Comment