标签:
1 /// <summary> 2 /// XML 序列化Helper 3 /// </summary> 4 public class XmlHelper 5 { 6 /// <summary> 7 /// 序列化 8 /// </summary> 9 /// <typeparam name="T">泛型</typeparam> 10 /// <param name="obj">对象</param> 11 /// <returns>字符串</returns> 12 public static string Serialize<T>(T obj) 13 { 14 if (obj == null) 15 { 16 return string.Empty; 17 } 18 19 using (MemoryStream stream = new MemoryStream()) 20 { 21 using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default)) 22 { 23 var serializer = new XmlSerializer(typeof(T)); 24 XmlSerializerNamespaces xns = new XmlSerializerNamespaces(); 25 xns.Add(string.Empty, string.Empty); 26 serializer.Serialize(writer, obj, xns); 27 stream.Seek(0, SeekOrigin.Begin); 28 using (StreamReader reader = new StreamReader(stream, Encoding.Default)) 29 { 30 return reader.ReadToEnd(); 31 } 32 } 33 } 34 } 35 36 /// <summary> 37 /// 反序列化 38 /// </summary> 39 /// <typeparam name="T">泛型</typeparam> 40 /// <param name="xml">字符串</param> 41 /// <returns>对象</returns> 42 public static T Deserialize<T>(string xml) 43 { 44 using (MemoryStream stream = new MemoryStream()) 45 { 46 using (StreamWriter writer = new StreamWriter(stream, Encoding.Default)) 47 { 48 writer.Write(xml); 49 writer.Flush(); 50 stream.Seek(0, SeekOrigin.Begin); 51 var serializer = new XmlSerializer(typeof(T)); 52 return (T)serializer.Deserialize(stream); 53 } 54 } 55 } 56 }
标签:
原文地址:http://www.cnblogs.com/lyosaki88/p/4953896.html