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

284 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.