public static class XMLHelp
{
private static XElement _XElement;
private static XmlSerializer ser;
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static XElement XmlSerializer<T>(T obj)
{
try
{
ser = new XmlSerializer(obj.GetType());
Stream stream = new MemoryStream();
ser.Serialize(stream, obj);
stream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(stream))
{
_XElement = XElement.Load(reader);
}
stream.Close();
return _XElement;
}
catch
{
return null;
}
}
public static T XmlDeserialize<T>(XElement xe)
{
try
{
ser = new XmlSerializer(typeof(T));
return (T)ser.Deserialize(xe.CreateReader());
}
catch (Exception ex)
{
return default(T);
}
}
public static T XmlDeserialize<T>(Type t, string xe)
{
try
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xe)))
{
ser = new XmlSerializer(t);
return (T)ser.Deserialize(ms);
}
}
catch
{
return default(T);
}
}
public static T XmlDeserialize<T>(string xe)
{
try
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xe)))
{
ser = new XmlSerializer(typeof(T));
return (T)ser.Deserialize(ms);
}
}
catch
{
return default(T);
}
}
}
做一个系统很是烦躁,需要把数据存入记事本,另一个线程则定时把数据添加到数据库,为了减小数据库的压力。
在取出来用代码的方式进行实例化到类 太麻烦,于是写了通用方法。
使用示例:
List<T> ListT = Common.XMLHelp.XmlDeserialize<List<T>>(strSoure)