将xml字符串反序列化为DataSet
1 /// <summary> 2 /// 将字符串反序列化 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="text"></param> 6 /// <returns></returns> 7 public static T Deserialize<T>(string text) 8 { 9 try 10 { 11 XmlSerializer serializer = new XmlSerializer(typeof(T)); 12 MemoryStream ms = new MemoryStream(); 13 byte[] buffer = Encoding.UTF8.GetBytes(text); 14 ms.Write(buffer, 0, buffer.Length); 15 ms.Seek(0, SeekOrigin.Begin); 16 object obj = serializer.Deserialize(ms); 17 ms.Flush(); 18 ms.Close(); 19 if (obj != null) 20 { 21 return (T)obj; 22 } 23 } 24 catch (Exception ex) 25 { 26 } 27 return default(T); 28 }
将DataSet序列化为string
1 /// <summary> 2 /// 将对象序列化为字符串 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="obj"></param> 6 /// <returns></returns> 7 public static string Serialize<T>(T obj) 8 { 9 try 10 { 11 string xmlString = string.Empty; 12 XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 13 using (MemoryStream ms = new MemoryStream()) 14 { 15 xmlSerializer.Serialize(ms, obj); 16 xmlString = Encoding.UTF8.GetString(ms.ToArray()); 17 } 18 return xmlString; 19 20 } 21 catch (Exception ex) 22 { 23 throw ex; 24 } 25 return null; 26 27 }