检查URL是否是有效的Feed

Mah*_*asi 6 c# argotic feed

我正在使用Argotic Syndication Framework来处理Feed.

但问题是,如果我将URL传递给Argotic,这不是一个有效的Feed(例如,http://stackoverflow.com这是一个html页面,而不是feed),程序会挂起(我的意思是,Argotic停留在无限循环中)

那么,如何检查URL是否指向有效的Feed?

Aki*_*oto 7

从.NET 3.5开始,您可以在下面执行此操作.如果它不是有效的Feed,它将抛出异常.

using System.Diagnostics;
using System.ServiceModel.Syndication;
using System.Xml;

public bool TryParseFeed(string url)
{
    try
    {
        SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(url));

        foreach (SyndicationItem item in feed.Items)
        {
            Debug.Print(item.Title.Text);
        }
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以尝试自己解析文档:

string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<event>This is a Test</event>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
Run Code Online (Sandbox Code Playgroud)

然后尝试检查根元素.它应该是feed元素并具有" http://www.w3.org/2005/Atom "命名空间:

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
Run Code Online (Sandbox Code Playgroud)

参考文献:http : //msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx http://dotnet.dzone.com/articles/systemservicemodelsyndication