2012-02-17 88 views
1

我有一個包含SortedList<string, Data>私人領域,其中Data是一些intDateTimeNullable<DateTime>領域一個簡單的自定義類的類。序列化自定義類以XML

public class CustomCollection 
{ 
    private SortedList<string, Data> _list; 

    ... 
} 

現在,我會讓我的課序列化的,所以我可以寫的內容(即_list領域的項目)從現有的XML文件的XML文件或加載數據。

我該如何繼續?

我想我明白有兩種方法可以序列化:第一種方法是將所有字段標記爲可序列化,而第二種方法是實現IXmlSerializable接口。如果我理解正確,什麼時候可以使用這兩種方式?

+0

你是說你想從XML文件中加載_list的XML表示並將其保存到XML文件? – 2012-02-17 01:19:19

+0

@ Ricky.G:是的,這兩個_load from_和_save to_一個XML文件。 – enzom83 2012-02-17 01:21:01

+2

http://msdn.microsoft.com/en-us/magazine/cc164135.aspx可能會有所幫助。當我有時間時,我會爲你寫一些測試資源。 – findcaiyzh 2012-02-17 01:31:12

回答

4

好吧,你只需要用[Serializable]屬性來修飾你的類,它應該工作。但是你有它實現一個IDictionary而這些不能用IXmlSerializable的序列化一個排序列表所以需要做一些定製的看這裏

Serializing .NET dictionary

,但如果你改變你的排序列表到正常的列表或任何沒有實現一個IDictionary然後下面的代碼將工作:-)將它複製到控制檯應用程序並運行它。

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Data d = new Data { CurrentDateTime = DateTime.Now, DataId = 1 }; 
      Data d1 = new Data { CurrentDateTime = DateTime.Now, DataId = 2 }; 
      Data d2 = new Data { CurrentDateTime = DateTime.Now, DataId = 3 }; 

      CustomCollection cc = new CustomCollection 
             {List = new List<Data> {d, d1, d2}}; 

      //This is the xml 
      string xml = MessageSerializer<CustomCollection>.Serialize(cc); 

      //This is deserialising it back to the original collection 
      CustomCollection collection = MessageSerializer<CustomCollection>.Deserialize(xml); 
     } 
    } 

    [Serializable] 
    public class Data 
    { 
     public int DataId; 
     public DateTime CurrentDateTime; 
     public DateTime? CurrentNullableDateTime; 
    } 

    [Serializable] 
    public class CustomCollection 
    { 
     public List<Data> List; 
    } 

    public class MessageSerializer<T> 
    { 
     public static T Deserialize(string type) 
     { 
      var serializer = new XmlSerializer(typeof(T)); 

      var result = (T)serializer.Deserialize(new StringReader(type)); 

      return result; 
     } 

     public static string Serialize(T type) 
     { 
      var serializer = new XmlSerializer(typeof(T)); 
      string originalMessage; 

      using (var ms = new MemoryStream()) 
      { 
       serializer.Serialize(ms, type); 
       ms.Position = 0; 
       var document = new XmlDocument(); 
       document.Load(ms); 

       originalMessage = document.OuterXml; 
      } 

      return originalMessage; 
     } 
    } 
} 
+0

我認爲按順序讀取SortedList中的所有元素的一種方法是使用'foreach(KeyValuePair kvp in _list){//序列化一個元素}逐個枚舉它們'' – enzom83 2012-02-17 11:03:02

+1

您可以實現自己的自定義字典它擴展了現有的可序列化,請看這裏http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx – 2012-02-19 20:10:31