![](/img/trans.png)
[英]Root Element Missing when deserializing an XML response using XmlSerializer
[英]The error when deserializing the pubDate element of an RSS xml feed using XmlSerializer
當我嘗試使用XmlSerializer反序列化RSS xml的pubDate元素時,出現以下錯誤:
System.Xml.dll中發生了類型為'System.InvalidOperationException'的未處理異常
這是我反序列化時使用的類:
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; }
}
並且pubDate元素具有以下格式:
<pubDate>Sat, 29 Mar 2014 19:27:18 EDT</pubDate>
我究竟做錯了什么? 該錯誤的解決方法是什么?
看來您在使用日期時間格式時遇到了麻煩,也許可以使用DataType和DisplayFormat屬性對其進行修復,但是我將使用LINQ to XML
來代替:
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();
我對您的Date
字符串做了一些操作,因為無法在我的機器上正確解析它。也許您可以添加格式的K
指定符末尾,然后嘗試直接使用CultureInfo.CurrentCulture
對其進行解析,而無需使用Split
和Take
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.