1.XmlSerializer
症狀
用XmlSerializer進行xml反序列化的時候,程序報錯:
不應有 <xml xmlns=''>。
說明: 執行當前 Web 請求期間,出現未經處理的異常。請檢查堆棧跟蹤信息,以了解有關該錯誤以及代碼中導致錯誤的出處的詳細信息。
異常詳細信息: System.InvalidOperationException: 不應有 <xml xmlns=''>。
我的xml如下:
<xml> <ToUserName><![CDATA[gh_1874139df55e]]></ToUserName> <FromUserName><![CDATA[ov4latyc1pi0_Ics0uHY6QTLRDg8]]></FromUserName> <CreateTime>1388056811</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[哈哈]]></Content> <MsgId>5961658608245054071</MsgId> </xml>
要反序列化的對象類型:
public class WXP_Message { public int MessageId { get; set; } public string ToUserName { get; set; } public string FromUserName { get; set; } public DateTime CreateTime { get; set; } public string MsgType { get; set; } public string Event { get; set; } public string Content { get; set; } public string PicUrl { get; set; } public string Format { get; set; } public string Location_X { get; set; } public string Location_Y { get; set; } public string Scale { get; set; } public string Label { get; set; } public string Title { get; set; } public string Description { get; set; } public string Url { get; set; } public int MsgId { get; set; } public int MediaId { get; set; } public int ThumbMediaId { get; set; } public bool IsReplied { get; set; } public string ReplyContent { get; set; } public DateTime ReplyTime { get; set; } public bool IsGiftVoucher { get; set; } public int IntTime { get; set; } }
診斷
這個錯誤一般都是xml不能反序列化為目標對象類型造成的,我的這個原因是因為:xml的根節點(xml)和對象名(wxp_message)不一樣導致的不能反序列化。
解決
修改xml根節點和對象類名一樣就可以了
<WXP_Message> <ToUserName><![CDATA[gh_1874139df55e]]></ToUserName> <FromUserName><![CDATA[ov4latyc1pi0_Ics0uHY6QTLRDg8]]></FromUserName> <CreateTime>1388056811</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[哈哈]]></Content> <MsgId>5961658608245054071</MsgId> </WXP_Message>
參考鏈接:

http://www.jb51.net/article/6536.htm