Xml 序列化和反序列化
阿新 • • 發佈:2018-12-20
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 thrownew 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 }
參考