转载

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         }

序列化

 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         }
正文到此结束
Loading...