标签:
1 public class XmlSerializerHelper 2 { 3 /// <summary> 4 /// 从XML文件中反序列化读取对象 5 /// </summary> 6 /// <typeparam name="T"></typeparam> 7 /// <param name="filePath"></param> 8 /// <param name="rootElementName"></param> 9 /// <param name="ns"></param> 10 /// <returns></returns> 11 public static T Load<T>(string filePath, string rootElementName, string ns) 12 where T : class,new() 13 { 14 try 15 { 16 using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate)) 17 { 18 XmlSerializer ser = new XmlSerializer(typeof(T), new XmlRootAttribute 19 { 20 ElementName = rootElementName, 21 Namespace = ns 22 }); 23 return ser.Deserialize(stream) as T; 24 } 25 } 26 catch (Exception ex) 27 { 28 return new T(); 29 } 30 } 31 32 /// <summary> 33 /// 向XML文件中序列化对象 34 /// </summary> 35 /// <param name="filePath"></param> 36 /// <param name="o"></param> 37 /// <param name="rootElementName"></param> 38 /// <param name="ns"></param> 39 /// <returns></returns> 40 public static bool Save(string filePath, object o, string rootElementName, string ns) 41 { 42 try 43 { 44 using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate)) 45 { 46 XmlSerializer ser = new XmlSerializer(o.GetType(), new XmlRootAttribute 47 { 48 ElementName = rootElementName, 49 Namespace = ns 50 }); 51 ser.Serialize(stream, o); 52 return true; 53 } 54 } 55 catch (Exception ex) 56 { 57 return false; 58 } 59 } 60 }
标签:
原文地址:http://www.cnblogs.com/ziranquliu/p/4648790.html