基於發佈在bug report to Microsoft about this中的解決方法,我製作了專門用於閱讀具有非標準日期的SyndicationFeeds的XmlReader。
下面的代碼與Microsoft網站的解決方法中的代碼略有不同。使用RFC 1123模式也需要Oppositional's advice。
不是簡單地調用XmlReader.Create(),而是需要從Stream中創建XmlReader。我使用WebClient類來獲取流:
WebClient client = new WebClient();
using (XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(feedUrl)))
{
SyndicationFeed feed = SyndicationFeed.Load(reader);
....
//do things with the feed
....
}
下面是對SyndicationFeedXmlReader代碼:
public class SyndicationFeedXmlReader : XmlTextReader
{
readonly string[] Rss20DateTimeHints = { "pubDate" };
readonly string[] Atom10DateTimeHints = { "updated", "published", "lastBuildDate" };
private bool isRss2DateTime = false;
private bool isAtomDateTime = false;
public SyndicationFeedXmlReader(Stream stream) : base(stream) { }
public override bool IsStartElement(string localname, string ns)
{
isRss2DateTime = false;
isAtomDateTime = false;
if (Rss20DateTimeHints.Contains(localname)) isRss2DateTime = true;
if (Atom10DateTimeHints.Contains(localname)) isAtomDateTime = true;
return base.IsStartElement(localname, ns);
}
public override string ReadString()
{
string dateVal = base.ReadString();
try
{
if (isRss2DateTime)
{
MethodInfo objMethod = typeof(Rss20FeedFormatter).GetMethod("DateFromString", BindingFlags.NonPublic | BindingFlags.Static);
Debug.Assert(objMethod != null);
objMethod.Invoke(null, new object[] { dateVal, this });
}
if (isAtomDateTime)
{
MethodInfo objMethod = typeof(Atom10FeedFormatter).GetMethod("DateFromString", BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Assert(objMethod != null);
objMethod.Invoke(new Atom10FeedFormatter(), new object[] { dateVal, this });
}
}
catch (TargetInvocationException)
{
DateTimeFormatInfo dtfi = CultureInfo.CurrentCulture.DateTimeFormat;
return DateTimeOffset.UtcNow.ToString(dtfi.RFC1123Pattern);
}
return dateVal;
}
}
再次,這是從連接微軟網站上公佈的解決辦法複製幾乎一模一樣以上。 ...除了這一個適合我,而在微軟發佈的那個沒有。
注意:您可能需要做的一點定製是在類的開始處的兩個數組中。根據您的非標準提要可能添加的任何無關字段,您可能需要向這些數組添加更多項目。
內置的是可怕的。您可以輕鬆編寫您自己的RSS,RDF和ATOM解析器。我有一個教程和一個完整的視覺工作室項目,你可以下載,只是那個http://www.jarloo.com/rumormill-5/ – Kelly 2011-10-07 03:07:29