C# XML反序列化与序列化
1、首先我们建一个XmlUtil类,然后,提供四个方法,对字符串和文件进入反序列化与序列化

3、添加 将XML文件反序列化成对象方法public static T DeserializeFile<T>(string filePath, string xmlRootName = "Root"){ T result = default(T); if (File.Exists(filePath)) { using (StreamReader reader = new StreamReader(filePath)) { XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); result = (T)xmlSerializer.Deserialize(reader); } } return result;}

5、添加将对象序列化成XML文件方法public static void SerializerFile(string filePath, object sourceObj, string xmlRootName = "Root"){ if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null) { Type type = sourceObj.GetType(); using (StreamWriter writer = new StreamWriter(filePath)) { XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName)); xmlSerializer.Serialize(writer, sourceObj); } }}

7、对文件的序列化与反序列化测试//序列化XmlUtil.SerializerFile("./guoke.xml",list);//反序列化List<Data> tmpList = XmlUtil.DeserializeFile<List<Data>>("./guoke.xml");
