检查URL是否是有效的Feed

时间:2012-08-16 22:38:42

标签: c# feed argotic

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

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

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

4 个答案:

答案 0 :(得分: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;
    }
}

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

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

然后尝试检查根元素。它应该是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">

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

答案 1 :(得分:2)

您可以使用Feed Validation Service。它有SOAP API

答案 2 :(得分:1)

您可以查看内容类型。它必须是text/xml。请参阅this question以查找内容类型。

您可以使用此代码:

var request = HttpWebRequest.Create("http://www.google.com") as HttpWebRequest;
if (request != null)
{
    var response = request.GetResponse() as HttpWebResponse;

    string contentType = "";

    if (response != null)
        contentType = response.ContentType;
}

感谢the question

的回答

<强>更新

要检查它是否是Feed地址,您可以使用W3C Feed Validation服务。

<强> UPDATE2

正如BurundukXP所说,它有一个SOAP API。要使用它,您可以阅读this question的答案。

答案 3 :(得分:0)

如果只想将其转换为有效的RSS / ATOM,则可以使用http://feedcleaner.nick.pro/对其进行清理。或者,您可以fork the project

相关问题