Code
#region 注释
/*
作者:李杰
邮箱: zhuyuelee@163.com
主页:
日期:2008年10月28日 11:05:08
******************************************************************************************
功能描述:XML序列化底层类
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace Lee.Xml.DBUtility
{
/// <summary>
/// SerializationHelper 的摘要说明。
/// </summary>
public class SerializationHelper
{
/// <summary>
/// 返回操作信息
/// </summary>
public static string Message = "操作成功";
private SerializationHelper()
{
}
#region 反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">对象类型</param>
/// <param name="filename">文件路径</param>
/// <param name="root">根元素</param>
/// <returns></returns>
public static object Load(Type type, string filename, string root)
{
FileStream fs = null;
object obj = null;
try
{
// open the stream
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
XmlSerializer serializer;
if (root != null)
{
XmlRootAttribute xmlRoot = new XmlRootAttribute();
xmlRoot.ElementName = root;
serializer = new XmlSerializer(type, xmlRoot);
}
else
{
serializer = new XmlSerializer(type);
}
obj = serializer.Deserialize(fs);
}
catch (Exception e)
{
Message = e.Message;
}
finally
{
if (fs != null)
fs.Close();
}
return obj;
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">对象类型</param>
/// <param name="filename">文件路径</param>
/// <returns></returns>
public static object Load(Type type, string filename)
{
return Load(type, filename, null);
}
#endregion
#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj">对象</param>
/// <param name="filename">文件路径</param>
/// <param name="Root">根元素</param>
/// <returns></returns>
public static bool Save(object obj, string filename, string root)
{
bool reResult = true;
FileStream fs = null;
// serialize it
try
{
fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
XmlSerializer serializer;
if (root != null)
{
XmlRootAttribute xmlRoot = new XmlRootAttribute();
xmlRoot.ElementName = root;
serializer = new XmlSerializer(obj.GetType(), xmlRoot);
}
else
{
serializer = new XmlSerializer(obj.GetType());
}
serializer.Serialize(fs, obj);
}
catch (Exception ex)
{
Message = ex.Message;
}
finally
{
if (fs != null)
fs.Close();
}
return reResult;
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj">对象</param>
/// <param name="filename">文件路径</param>
public static bool Save(object obj, string filename)
{
return Save(obj, filename, null);
}
#endregion
}
}