XML序列化和反序列化
public static class XmlHelper{
/// <summary>
/// 将对象保存为xml文件
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="path">保存文件的路径及文件名如“C:\test.xml”</param>
/// <param name="obj">要保存对象的实例</param>
/// <param name="xmlRootName">跟节点名</param>
public static void EntitySaveToXml<T>(string path, T obj, string xmlRootName =null )
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path 不能为空!");
}
if (obj == null){
throw new ArgumentNullException("obj 不能为空!");
}
using (FileStream fs = new FileStream(path, FileMode.Create))
{
var type = typeof(T);
var xmlSerializer = string.IsNullOrEmpty(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, xmlRootName);
xmlSerializer.Serialize(fs, obj);
fs.Close();
fs.Dispose();
}
}
/// <summary>
/// 将xml文件发序列化为对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="path">xml路径如“C:\test.xml”</param>
/// <param name="xmlRootName">xml根节点名</param>
/// <returns>对象实例</returns>
public static T XmlToEntity<T>(string path, string xmlRootName=null)
{
T result;
if (File.Exists(path))
{
using (StreamReader sr = new StreamReader(path))
{
var type = typeof(T);
var xmlSerializer = string.IsNullOrEmpty(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, xmlRootName);
result = (T)xmlSerializer.Deserialize(sr);
sr.Close();
sr.Dispose();
}
}
else
{
throw new Exception("文件不存在!");
}
return result;
}
} 谢谢楼主分享 ~~~~~~~~~~~~~`
页:
[1]