c#的序列化与反序列化

利用泛型实现序列化与反序列化

反序列化(path为xml文件路径)

 1  public static List<T> GetXmlData(string path)
 2         {
 3             if (File.Exists(path))
 4             {
 5                 XmlSerializer xml = new XmlSerializer(typeof(List<T>));
 6                 using (StreamReader w = new StreamReader(path))
 7                 {
 8                     List<T> list = xml.Deserialize(w) as List<T>;
 9                     return list;
10                 }
11             }
12             return new List<T>();
13         }

序列化,如果xml文件存在,则被覆盖

 1  public static void Serialize(List<T> list,string path)
 2         {
 3             XmlSerializer lizer = new XmlSerializer(typeof(List<T>));
 4             
 5             using (System.IO.StreamWriter writer = new System.IO.StreamWriter(path))
 6             {
 7                 System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));
 8                 xs.Serialize(writer, list);
 9                 writer.Close();
10             }
11         }

 

posted @ 2015-07-31 08:43  JustFoi  阅读(587)  评论(0)    收藏  举报