2011-03-10 235 views
1

我有一個XML文件,該文件的格式如下XML反序列化

"<rundate> 

    <rundateItem> 
    <LeaveCreditingMonth>2</LeaveCreditingMonth> 
    <LeaveCreditingYear>2010</LeaveCreditingYear> 
    <IncludeNoTimesheet>True</IncludeNoTimesheet> 
    </rundateItem> 

</rundate>" 

的情況下,我想反序列化這個XML文件,應該是什麼類別或反序列化我的目標對象的格式? 目前我的課是這樣的:

public class rundate 
    { 

     string _leaveCreditingMonth; 
     string _leaveCreditingYear; 
     string _includeNoTimesheet; 

     public string LeaveCreditingMonth {get{return _leaveCreditingMonth;}set{ _leaveCreditingMonth = value;}} 
     public string LeaveCreditingYear {get{return _leaveCreditingYear;}set{ _leaveCreditingYear = value;}} 
     public string IncludeNoTimesheet {get{return _includeNoTimesheet;}set{ _includeNoTimesheet = value;}} 

    } 

回答

3

你的類可以留爲是的(顯然你應該改變數據類型爲合適的) - 因爲你有嵌套在你的XML中(這意味着可以有多個)rundate我建議添加一個收集離子類,如下所示:

[XmlRoot("rundate")] 
public class RundateCollection 
{ 
    [XmlElement("rundateItem")] 
    public List<rundate> Rundates { get; set; } 
} 

您可以測試序列化/與你的XML反序列化類,如下所示:

XmlSerializer serializer = new XmlSerializer(typeof(RundateCollection)); 
StringWriter sw = new StringWriter(); 
rundate myRunDate = new rundate() { LeaveCreditingMonth = "A", IncludeNoTimesheet = "B", LeaveCreditingYear = "C" }; 
RundateCollection ra = new RundateCollection() { Rundates = new List<rundate>() { myRunDate } }; 
serializer.Serialize(sw, ra); 
string xmlSerialized = sw.GetStringBuilder().ToString(); 
string xml = File.ReadAllText(@"test.xml"); 
StringReader sr = new StringReader(xml); 
var rundateCollection = serializer.Deserialize(sr); 

您將看到集合類是已成功從您的XML反序列化,幷包含一個列表項目類型runlist

+0

非常感謝..它真的有很大幫助.. – Lemuel 2011-03-10 07:00:54

2

我會設計類,像這樣:

public class Rundate 
    { 

     public int LeaveCreditingMonth { get; set;} 
     public int LeaveCreditingYear { get; set; } 
     public bool IncludeNoTimesheet { get; set; } 

    } 

然後你可以反序列化這樣的:

var serializer = new XmlSerializer(typeof(List<Rundate>)); 
using (var fs = new FileStream("yourfile.xml", FileMode.Open)) 
{ 
    using (var reader = new XmlTextReader(fs)) 
    { 
     var rundates = (List<Rundate>)serializer.Deserialize(reader); 
    } 
}