症狀
用XmlSerializer進行xml反序列化的時候,程序報錯:
不應有 <xml xmlns=''>。
說明: 執行當前 Web 請求期間,出現未經處理的異常。請檢查堆棧跟蹤信息,以了解有關該錯誤以及代碼中導致錯誤的出處的詳細信息。
異常詳細信息: System.InvalidOperationException: 不應有 <xml xmlns=''>。
我的xml如下:
1 |
<xml><ToUserName><![CDATA[gh_1874139df55e]]></ToUserName> |
2 |
<FromUserName><![CDATA[ov4latyc1pi0_Ics0uHY6QTLRDg8]]></FromUserName> |
3 |
<CreateTime>1388056811</CreateTime> |
4 |
<MsgType><![CDATA[text]]></MsgType> |
5 |
<Content><![CDATA[哈哈]]></Content> |
6 |
<MsgId>5961658608245054071</MsgId> |
7 |
</xml> |
要反序列化的對象類型:
01 |
public class WXP_Message |
02 |
{ |
03 |
public int MessageId { get; set; } |
04 |
05 |
public string ToUserName { get; set; } |
06 |
07 |
public string FromUserName { get; set; } |
08 |
09 |
public DateTime CreateTime { get; set; } |
10 |
11 |
public string MsgType { get; set; } |
12 |
13 |
public string Event { get; set; } |
14 |
15 |
public string Content { get; set; } |
16 |
17 |
public string PicUrl { get; set; } |
18 |
19 |
public string Format { get; set; } |
20 |
21 |
public string Location_X { get; set; } |
22 |
23 |
public string Location_Y { get; set; } |
24 |
25 |
public string Scale { get; set; } |
26 |
27 |
public string Label { get; set; } |
28 |
29 |
public string Title { get; set; } |
30 |
31 |
public string Description { get; set; } |
32 |
33 |
public string Url { get; set; } |
34 |
35 |
public int MsgId { get; set; } |
36 |
37 |
public int MediaId { get; set; } |
38 |
39 |
public int ThumbMediaId { get; set; } |
40 |
41 |
public bool IsReplied { get; set; } |
42 |
43 |
public string ReplyContent { get; set; } |
44 |
45 |
public DateTime ReplyTime { get; set; } |
46 |
47 |
public bool IsGiftVoucher { get; set; } |
48 |
49 |
public int IntTime { get; set; } |
50 |
51 |
} |
診斷
這個錯誤一般都是xml不能反序列化為目標對象類型造成的,我的這個原因是因為:xml的根節點(xml)和對象名(wxp_message)不一樣導致的不能反序列化
解決
修改xml根節點和對象類名一樣就可以了
1 |
<WXP_Message><ToUserName><![CDATA[gh_1874139df55e]]></ToUserName> |
2 |
<FromUserName><![CDATA[ov4latyc1pi0_Ics0uHY6QTLRDg8]]></FromUserName> |
3 |
<CreateTime>1388056811</CreateTime> |
4 |
<MsgType><![CDATA[text]]></MsgType> |
5 |
<Content><![CDATA[哈哈]]></Content> |
6 |
<MsgId>5961658608245054071</MsgId> |
7 |
</WXP_Message> |
