在 SyndicationFeed 中解析 DateTime 值
本文关键字:DateTime SyndicationFeed | 更新日期: 2023-09-27 18:34:21
我使用以下代码来解析原子馈送:
using(var reader = new MyXmlReader("http://tutsplus.com/courses.atom")) {
var doc = SyndicationFeed.Load(reader);
var newFeed = new AtomFeed {
Id = doc.Id,
Title = doc.Title.Text,
Url = url,
UpdateDate = DateTime.Now
};
XNamespace dc = "http://www.w3.org/2005/Atom";
newFeed.AtomEntries = (from entry in doc.Items
select new AtomEntry {
Id = entry.Id,
Links = entry.Links,
Title = entry.Title.Text,
Content = entry.Content.ToString(),
PublishDate = entry.PublishDate.DateTime,
UpdatedDate = entry.LastUpdatedTime.DateTime,
Authors = entry.Authors
}).ToList();
}
似乎在我的提要中未将字符串识别为有效的日期时间。我也知道 (+) SyndicationFeed.Load
方法期望接收标准格式的提要,如下所示:Mon, 05 Oct 2015 08:00:06 GMT
.因此,我创建了可识别不同日期格式的自定义 XML 读取器。但仍然有同样的错误!
知道吗?
当我尝试使用您链接的自定义 XML 阅读器时,我在解析"发布"和"更新"日期时也遇到了此错误。查看Atom10FeedFormatter
类的代码,它正在尝试解析这些格式的日期(DateFromString
方法)
const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz";
const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
http://reflector.webtropy.com/default.aspx/WCF/WCF/3@5@30729@1/untmp/Orcas/SP/ndp/cdf/src/NetFx35/System@ServiceModel@Web/System/ServiceModel/Syndication/Atom10FeedFormatter@cs/2/Atom10FeedFormatter@cs
所以我在 MyXmlReader
实现中更改了该格式以yyyy-MM-ddTHH:mm:ssZ
设置该格式,然后这个日期解析一切都很好(我还必须更改ReadStartElement
元素名称以将readingDate
设置为等于 true,即发布和更新)。
public override string ReadString()
{
if (readingDate)
{
string dateString = base.ReadString();
DateTime dt;
if (!DateTime.TryParse(dateString, out dt))
dt = DateTime.ParseExact(dateString, CustomUtcDateTimeFormat, CultureInfo.InvariantCulture);
return dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
}
else
{
return base.ReadString();
}
}