保存object到xml

对实体类做标记

[DataContract] 标记在class前。

[DataMember] 标记在需要保存的属性前。

 1 [DataContract]
 2public class Car
 3{
 4  [DataMember]
 5  public string name;
 6
 7  [DataMember]
 8  double power;
 9
10  [DataMember]
11  List<Wheel> wheels;
12}

拷贝这两个函数

保存:保存文件到xml,文件目录和程序目录相同,文件名自定。

读取:从指定文件名读取。

 1static void SaveViaDataContractSerialization<T>(T serializableObject, string filepath)
 2{
 3  var serializer = new DataContractSerializer(typeof(T));
 4  var settings = new XmlWriterSettings()
 5  {
 6    Indent = true,
 7    IndentChars = "\t",
 8  };
 9  var writer = XmlWriter.Create(filepath, settings);
10  serializer.WriteObject(writer, serializableObject);
11  writer.Close();
12}
13
14
15static T LoadViaDataContractSerialization<T>(string filepath)
16{
17  var fileStream = new FileStream(filepath, FileMode.Open);
18  var reader = XmlDictionaryReader.CreateTextReader(fileStream, new XmlDictionaryReaderQuotas());
19  var serializer = new DataContractSerializer(typeof(T));
20  T serializableObject = (T)serializer.ReadObject(reader, true);
21  reader.Close();
22  fileStream.Close();
23  return serializableObject;
24}

读取方法

使用上面两个方法来读取和存储

 1// Save single object
 2Car bmw = new Car("BMW", 200, new List<string> { "Left", "Right" });    // create object
 3SaveViaDataContractSerialization(bmw, "bmw.xml");                       // save object
 4bmw = null;                                                             // delete object
 5bmw = LoadViaDataContractSerialization<Car>("bmw.xml");                 // reload object
 6Console.WriteLine(bmw.ToString());                                      // print object
 7
 8
 9// Save list of objects
10List<Car> carList = new List<Car>                                       // create object list
11{
12new Car("Porsche", 250, new List<string> { "Left" }),
13new Car("Mercedes", 150, new List<string> { "Front", "Back" }),
14new Car("Aston Martin", 300, new List<string> { "Front" })
15};
16SaveViaDataContractSerialization(carList, "cars.xml");                  // save object list
17carList = null;                                                         // delete object list
18carList = LoadViaDataContractSerialization<List<Car>>("cars.xml");      // reload object list
19foreach (var a in carList)                                              // print object list
20Console.WriteLine(a.ToString());
21
22Console.ReadLine();

原视频:https://www.youtube.com/watch?v=GzZu3eYDBmM

demo代码:https://pastebin.com/mRTmdiK5


Corntab计划任务
Linkedlist删除指定值