Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two SyndicationFeeds

Tags:

c#

linq

.net-3.5

What's a simple way to combine feed and feed2? I want the items from feed2 to be added to feed. Also I want to avoid duplicates as feed might already have items when a question is tagged with both WPF and Silverlight.

Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri);
SyndicationFeed feed = SyndicationFeed.Load(reader);    

Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri);
SyndicationFeed feed2 = SyndicationFeed.Load(reader2);
like image 579
Alan Le Avatar asked Sep 17 '08 02:09

Alan Le


2 Answers

You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ServiceModel.Syndication;

namespace FeedUnion
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight"); 
            SyndicationFeed feed;
            SyndicationFeed feed2;
            using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri))
            {
                feed= SyndicationFeed.Load(reader); 
            }
            Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf"); 
            using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))
            {
            feed2 = SyndicationFeed.Load(reader2);
            }
            SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items));
            StringBuilder builder = new StringBuilder();
            using (XmlWriter writer = XmlWriter.Create(builder))
            {
                feed3.SaveAsRss20(writer);
                System.Console.Write(builder.ToString());
                System.Console.Read();
            }
        }
    }
}
like image 153
Michael Brown Avatar answered Nov 03 '22 19:11

Michael Brown


Well, one possibility is to create a new syndication feed that is a clone of the first feed, and then simply iterate through each post on the second one, check the first for its existence, and add it if it doesn't exist.

Something along the lines of:

SyndicationFeed newFeed = feed.clone;
foreach(SyndicationItem item in feed2.items)
{
  if (!newFeed.contains(item))
    newFeed.items.Add(item);
}

might be able to do it. It looks like 'items' is a simple enumberable list of syndication items, so theres not reason you can't simply add them.

like image 1
Frater Avatar answered Nov 03 '22 19:11

Frater