using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace CommonHelper
{
public class Serialize
{
/// <summary>
/// 序列化对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="t">对象</param>
/// <returns></returns>
public static string XmlSerialize<T>(T t)
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer xz = new XmlSerializer(t.GetType());
xz.Serialize(sw, t);
return sw.ToString();
}
}
/// <summary>
/// 序列化对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="t">对象</param>
/// <returns></returns>
public static string XmlSerialize(object t)
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer xz = new XmlSerializer(t.GetType());
xz.Serialize(sw, t);
return sw.ToString();
}
}
/// <summary>
/// 反序列化为对象
/// </summary>
/// <param name="type">对象类型</param>
/// <param name="s">对象序列化后的Xml字符串</param>
/// <returns></returns>
public static T XmlDeserialize<T>(Type type, string s)
{
using (StringReader sr = new StringReader(s))
{
XmlSerializer xz = new XmlSerializer(type);
return (T)xz.Deserialize(sr);
}
}
}
}