是否可以从System.ServiceModel.Syndication.SyndicationFeed实例确定正在读取什么类型的SyndicationFeed?如果我只有url(blahblah.com/feed)它可能是rss或atom,并且取决于我想做一件事或另一件事的类型。
有没有一种简单的方法可以在不解析文档和查找特定字符的情况下判断?
答案 0 :(得分:9)
老问题,但值得回答。
是一种相对简单的方法来确定您是否拥有RSS或Atom Feed。它确实需要阅读或尝试阅读文档。
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;
}
}