Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine feed type of a .NET SyndicationFeed (RSS vs Atom)?

Is it possible to determine from the System.ServiceModel.Syndication.SyndicationFeed instance what type of SyndicationFeed is being read? If all I have is the url (blahblah.com/feed) it might be rss or atom, and depending on the type I want to do one thing or the other.

Is there a simple way to tell without parsing the document and looking for specific characters?

like image 620
SelAromDotNet Avatar asked Jun 10 '10 02:06

SelAromDotNet


1 Answers

Old question, but it deserves an answer.

There is a relatively simple way to determine if you've got an RSS or an Atom feed. It does require reading, or trying to read the document.

public SyndicationFeed GetSyndicationFeedData(string urlFeedLocation)
{
    XmlReaderSettings settings = new XmlReaderSettings
        {
            IgnoreWhitespace = true,
            CheckCharacters = true,
            CloseInput = true,
            IgnoreComments = true,
            IgnoreProcessingInstructions = true, 
            //DtdProcessing = DtdProcessing.Prohibit // .NET 4.0 option
        };

    if (String.IsNullOrEmpty(urlFeedLocation))
        return null;

    using (XmlReader reader = XmlReader.Create(urlFeedLocation, settings))
    {
        if (reader.ReadState == ReadState.Initial)
            reader.MoveToContent();

        // now try reading...

        Atom10FeedFormatter atom = new Atom10FeedFormatter();
        // try to read it as an atom feed
        if (atom.CanRead(reader))
        {
            atom.ReadFrom(reader);
            return atom.Feed;
        }

        Rss20FeedFormatter rss = new Rss20FeedFormatter();
        // try reading it as an rss feed
        if (rss.CanRead(reader))
        {
            rss.ReadFrom(reader);
            return rss.Feed;
        }

        // neither?
        return null;
    }
}
like image 107
Cheeso Avatar answered Sep 19 '22 06:09

Cheeso