Xml 序列化和反序列化
发布时间:2020-12-16 23:39:42 所属栏目:百科 来源:网络整理
导读:xml序列化帮助类 using System.IO; using System.Xml; using System.Xml.Serialization; ? 1 public class XmlHelper 2 { 3 public static T DeserializeT (String file) 4 { 5 if (! File.Exists(file)) 6 { 7 throw new FileNotFoundException(); 8 } 9 10
xml序列化帮助类 using System.IO; using System.Xml; using System.Xml.Serialization; ? 1 public class XmlHelper 2 { 3 public static T Deserialize<T>(String file) 4 { 5 if (!File.Exists(file)) 6 { 7 throw new FileNotFoundException(); 8 } 9 10 T obj; 11 using (FileStream fs = new FileStream(file,FileMode.Open)) 12 { 13 XmlSerializer xml = new XmlSerializer(typeof(T)); 14 obj = (T)xml.Deserialize(fs); 15 fs.Close(); 16 } 17 return obj; 18 } 19 20 21 #region 序列化 22 /// <summary> 23 /// 序列化 24 /// </summary> 25 /// <param name="type">类型</param> 26 /// <param name="obj">对象</param> 27 /// <returns></returns> 28 public static string Serializer<T>(object obj) 29 { 30 using (MemoryStream stream = new MemoryStream()) 31 { 32 XmlSerializer xml = new XmlSerializer(typeof(T)); 33 //序列化对象 34 xml.Serialize(stream,obj); 35 stream.Position = 0; 36 using (StreamReader sr = new StreamReader(stream)) 37 { 38 string str = sr.ReadToEnd(); 39 return str; 40 } 41 } 42 } 43 public static void Serializer<T>(String saveFile,T obj) 44 { 45 XmlSerializer serializer = new XmlSerializer(typeof(T)); 46 using (FileStream stream = new FileStream(saveFile,FileMode.Create)) 47 { 48 serializer.Serialize(stream,obj); 49 } 50 } 51 /// <summary> 52 /// 将一个对象序列化为XML字符串 53 /// </summary> 54 /// <param name="obj">要序列化的对象</param> 55 /// <param name="encoding">编码方式</param> 56 /// <returns>序列化产生的XML字符串</returns> 57 public static void XmlSerialize(object obj,string xml,Encoding encoding) 58 { 59 if (encoding == null) 60 throw new ArgumentNullException("encoding"); 61 62 using (FileStream stream = new FileStream(xml,FileMode.Create)) 63 { 64 XmlWriterSettings settings = new XmlWriterSettings(); 65 settings.Encoding = encoding; 66 settings.Indent = true;//缩进和换行 67 using (XmlWriter writer = XmlWriter.Create(stream,settings)) 68 { 69 XmlSerializer serializer = new XmlSerializer(obj.GetType()); 70 serializer.Serialize(writer,obj); 71 } 72 } 73 } 74 75 #endregion 76 } ? 参考 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |