using System; using System.IO; using System.Xml.Serialization; namespace PaintDotNet.Base.CommTool { /// /// XML序列化公共处理类 /// public static class XmlSerializeHelper { /// /// 将实体对象转换成XML /// /// 实体类型 /// 实体对象 public static string XmlSerialize(T obj) { try { using (StringWriter sw = new StringWriter()) { Type t = obj.GetType(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(sw, obj); sw.Close(); return sw.ToString(); } } catch (Exception ex) { throw new Exception("", ex); // ("将实体对象转换成XML异常", ex); //("", exception); // } } /// /// 将XML转换成实体对象 /// /// 实体类型 /// XML public static T DESerializer(string strXML) where T : class { try { using (StringReader sr = new StringReader(strXML)) { XmlSerializer serializer = new XmlSerializer(typeof(T)); return serializer.Deserialize(sr) as T; } } catch (Exception ex) { throw new Exception("", ex); // ("将XML转换成实体对象异常", ex); } } /// /// 将实体对象转换成XML /// /// 实体类型 /// 实体对象 public static void Save(T obj, string path) { try { using (var wirter = new FileStream(path, (FileMode)FileAccess.Write)) { Type t = obj.GetType(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(wirter, obj); wirter.Close(); } } catch (Exception ex) { throw new Exception("", ex); } } /// /// 将XML转换成实体对象 /// /// 实体类型 /// XML public static T Load(string path) where T : class { try { using (var reader = new FileStream(path, FileMode.Open)) { XmlSerializer xml = new XmlSerializer(typeof(T)); var obj = xml.Deserialize(reader); reader.Close(); return obj as T; } } catch (Exception ex) { throw new Exception("", ex); } } } }