18
我已經嘗試了所有解決方案,我可以在SO和其他地方找到,但似乎無法弄清楚爲什麼這不起作用。XmlSerializer.Deserialize在列表<>項
一個XML字符串轉換爲對象的簡單易懂的反序列化,對象有一個屬性 - 列表:
[XmlTypeAttribute(AnonymousType = true)]
public class UpdateData
{
[XmlArrayItem(ElementName = "Updates")]
public List<Update> Updates { get; set; }
public UpdateData()
{
Updates = new List<Update>();
}
}
public class Update
{
[XmlElement(ElementName = "MemberID")]
public int MemberID { get; set; }
[XmlElement(ElementName = "AnalysisID")]
public int AnalysisID { get; set; }
[XmlElement(ElementName = "MemberName")]
public string MemberName { get; set; }
[XmlElement(ElementName = "RecordDate")]
public DateTime RecordDate { get; set; }
}
這裏是反序列化代碼:
private object DeserialzeXml(string xml)
{
var xmlSer = new XmlSerializer(typeof(UpdateData), new XmlRootAttribute("UpdateData"));
var stringReader = new StringReader(xml);
return xmlSer.Deserialize(stringReader);
}
這裏是XML:
<?xml version="1.0" encoding="utf-8" ?>
<UpdateData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Updates>
<Update>
<MemberID>1</MemberID>
<AnalysisID>1</AnalysisID>
<MemberName>XXXXXXXXXXXXX</MemberName>
</Update>
<Update>
<MemberID>1</MemberID>
<AnalysisID>2</AnalysisID>
<MemberName>YYYYYYYYYYYYY</MemberName>
</Update>
<Update>
<MemberID>1</MemberID>
<AnalysisID>3</AnalysisID>
<MemberName>ZZZZZZZZZZZZ</MemberName>
</Update>
</Updates>
</UpdateData>
此代碼編譯並運行,並返回UpdateData類型的對象,但Up日期屬性爲空。有任何想法嗎?
感謝布賴恩,作品一種享受...是時候打我的頭靠在牆上。 – staterium 2010-01-18 14:36:06