简体   繁体   中英

Parsing a DateTime value in the SyndicationFeed

I'm using below code for parsing an atom feed:

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();

}

Seems that a string was not recognized as a valid DateTime in my feed. I'm also aware ( + ) that The SyndicationFeed.Load method expects to receive feeds that are in standard format like this: Mon, 05 Oct 2015 08:00:06 GMT . So I created my custom XML reader that recognizes different date formats. But still have same error!
Any idea?

When I tried it, with your linked custom XML reader, I also got this error when it came to parsing the "published" and "updated" dates. Looking at the code for the Atom10FeedFormatter class, it is trying to parse dates in these formats ( DateFromString method)

    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

So I changed in the MyXmlReader implementation to set that format yyyy-MM-ddTHH:mm:ssZ , then all is well with this date parsing (I also had to change in ReadStartElement the element names to set readingDate equal to true, ie published and updated).

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM