经常将对象实例序列化为xml文件,将xml反序列化为对象。随写成公共方法供调用。
1 public static class XmlHelper 2 { 3 /// <summary> 4 /// 将对象保存为xml文件 5 /// </summary> 6 /// <typeparam name="T">对象类型</typeparam> 7 /// <param name="path">保存文件的路径及文件名如“C:/test.xml”</param> 8 /// <param name="obj">要保存对象的实例</param> 9 /// <param name="xmlRootName">跟节点名</param>10 public static void EntitySaveToXml<T>(string path, T obj, string xmlRootName =null )11 {12 if (string.IsNullOrEmpty(path))13 {14 throw new ArgumentNullException("path 不能为空!");15 }16 if (obj == null){17 throw new ArgumentNullException("obj 不能为空!");18 }19 20 using (FileStream fs = new FileStream(path, FileMode.Create))21 {22 var type = typeof(T);23 var xmlSerializer = string.IsNullOrEmpty(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, xmlRootName);24 xmlSerializer.Serialize(fs, obj);25 fs.Close();26 fs.Dispose();27 }28 }29 30 /// <summary>31 /// 将xml文件发序列化为对象32 /// </summary>33 /// <typeparam name="T">对象类型</typeparam>34 /// <param name="path">xml路径如“C:/test.xml”</param>35 /// <param name="xmlRootName">xml根节点名</param>36 /// <returns>对象实例</returns>37 public static T XmlToEntity<T>(string path, string xmlRootName=null)38 {39 T result;40 if (File.Exists(path))41 {42 using (StreamReader sr = new StreamReader(path))43 {44 var type = typeof(T);45 var xmlSerializer = string.IsNullOrEmpty(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, xmlRootName);46 result = (T)xmlSerializer.Deserialize(sr);47 sr.Close();48 sr.Dispose();49 }50 }51 else52 {53 throw new Exception("文件不存在!");54 }55 return result;56 }57 }
C#对象XML序列化(一):序列化方法和常用特性
c# XML序列化与反序列化
在博客园,混迹多年从未写过博客,今第一次写博客,水平很差,望大牛斧正。
新闻热点
疑难解答