反序列化部分工作時出現問題。當我有一個帶屬性的xml節點時,所有屬性值都會正確加載到我的類中,但是當我使用元素時,它只會返回null。反序列化數組總是爲元素返回null,但使用屬性
我有以下的存儲在XML文件:
<?xml version="1.0" encoding="utf-8"?>
<email>
<from>[email protected]</from>
<recipients>
<recipient>[email protected]</recipient>
<recipient>[email protected]</recipient>
</recipients>
<subject>Test subject</subject>
<body>Test body</body>
<attachments>
<attachment>c:\test.txt</attachment>
<attachment>c:\test1.txt</attachment>
<attachment>c:\test2.txt</attachment>
</attachments>
</email>
我的主類的定義如下:
[Serializable]
[XmlRoot("email")]
public class EmailNotification
{
[XmlElement("from")]
public string From { get; set; }
[XmlElement("subject")]
public string Subject { get; set; }
[XmlElement("body")]
public string Body { get; set; }
[XmlArray("recipients")]
[XmlArrayItem("recipient")]
public List<EmailNotificationRecipient> Recipients { get; set; }
[XmlArray("attachments")]
[XmlArrayItem("attachment")]
public List<EmailNotificationAttachment> Attachments { get; set; }
public EmailNotification()
{
this.Attachments = new List<EmailNotificationAttachment>();
this.Recipients = new List<EmailNotificationRecipient>();
}
}
這裏是我的收件人類:
[Serializable]
public class EmailNotificationRecipient
{
public EmailNotificationRecipient()
{
}
[XmlElement("recipient")]
public string Recipient { get; set; }
}
我我不打算顯示附件類,因爲它與定義爲收件人類相同。
所有簡單的元素都被正確填充,我的數組正在構建,但其中的所有元素都是空的。
調試時,我可以看到我的數組有2個收件人項目和3個附件項目,但是當我檢查裏面的值時,每個數組項目都是空的。
我還添加了一個構造函數EmailNotificationRecipient類,並在其上設置了一個斷點,並且每次爲每個定義的收件人命中我的斷點。
有了上面的2點,它會讓你相信所有的東西都可以用我的類定義,或者它不會設法找到正確數量的元素,但是如前所述,我的數組中的所有對象都設置爲null,即使正確數量的對象被創建。
原來我和他們的類型定義的XmlArrayItem
:
[XmlArrayItem("recipient", typeof(EmailNotificationRecipient))]
public List<EmailNotificationRecipient> Recipients { get; set; }
我刪除它,看看它是否會作出任何區別,但都無濟於事。
我錯過了什麼?這是駕駛我的瘋狂!
謝謝。
UPDATE
請參閱從@NoIdeaForName回答以下。
的方式我現在有這規定將意味着,爲了它返回一個值,我的XML應該看起來像:
<recipients>
<recipient><recipient></recipient></recipient>
</recipients>
因爲我的數組實際上是在當所有期待一個類收件人我在每個接收節點是一個字符串,所以陣列應該被定義如下:
[XmlArray("recipients")]
[XmlArrayItem("recipient")]
public List<string> Recipients { get; set; }
現在,另一方面,如果每個我在我的XML收件人是這樣定義的:
<recipients>
<recipient>
<fname><fname>
<lname><lname>
</recipient>
</recipients>
那麼按照我的方式定義一個單獨的類是有意義的,即EmailNativeiationRecipient,但不是讓收件人作爲一個屬性,你應該有fname和lname。
再次感謝@NoIdeaForName :)
是EmailNotificationAttachment可串行化?如果不是,那就是你的問題。補充說,收件人標籤的內部沒有任何標籤,所以我不認爲解串器知道如何處理它 – 2014-11-05 13:18:00
我會寫一個答案,但我不能檢查它ATM,所以我知道發生了什麼所以我會知道如果刪除它 – 2014-11-05 13:20:41