简体   繁体   中英

The error when deserializing the pubDate element of an RSS xml feed using XmlSerializer

When I try to deserialize the pubDate element of an RSS xml, using XmlSerializer, i get this error:

An unhandled exception of type 'System.InvalidOperationException' occured in System.Xml.dll

This is the class i use while deserializing:

    public class RssItem
{
    [XmlElement("title")]
    public string Title { get; set; }

    [XmlElement("description")]
    public string Description { get; set; }

    [XmlElement("pubDate")]
    public DateTime Date { get; set; }

    [XmlElement("link")]
    public string Link { get; set; }
}

and the pubDate element has this format:

<pubDate>Sat, 29 Mar 2014 19:27:18 EDT</pubDate>  

What am i doing wrong? What is the solution to this error?

It seems you have some trouble with the datetime format maybe you can fix it using DataType and DisplayFormat attributes but I would use LINQ to XML instead:

var rssItems = XDocument.Load("path or URL")
                .Descendants("item")
                .Select(x => new RssItem
                {
                    Title = (string) x.Element("title"),
                    Description = (string) x.Element("description"),
                    Date = DateTime.ParseExact(string.Join(" ",x.Element("pubDate").Value.Split().Take(5)), "ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                    Link = (string) x.Element("link")
                }).ToList();

I did some manipulations on your Date string, because I couldn't parse it correctly on my machine.maybe you can add the K specifier end of the format and try parsing it with CultureInfo.CurrentCulture directly, without using Split and Take .

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