1、首先我们建一个XmlUtil类,然后,提供四个方法,对字符串和文件进入反序列化与序列化
2、添加 将XML字符串反序列化成对象方法public static T Deserialize<T>(string xml, string xmlRootName = "Root"){ T result = default(T); using (StringReader sr = new StringReader(xml)) { XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); result = (T)xmlSerializer.Deserialize(sr); } return result;}
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;}
4、添加将对象序列化成XML字符串方法public static string Serializer(object sourceObj, string xmlRootName = "Root"){ MemoryStream Stream = new MemoryStream(); Type type = sourceObj.GetType(); XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName)); xmlSerializer.Serialize(Stream, sourceObj); Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str;}
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); } }}
6、对字符串的序列化与反序列化测试//序列化string strTmp = XmlUtil.Serializer(data);//反序列化Data tmpData = XmlUtil.Deserialize<Data>(strTmp);
7、对文件的序列化与反序列化测试//序列化XmlUtil.SerializerFile("./guoke.xml",list);//反序列化List<Data> tmpList = XmlUtil.DeserializeFile<List<Data>>("./guoke.xml");