C# 将实体对象转换成XML
将实体对象转换成XML
using System;
using System.IO;
using System.Xml.Serialization;
namespace YG._CommonFunctions
{
///
/// 将实体对象转换成XML
///
public static class Class2XML
{
/// 实体类型
/// 实体对象
public static string ToXml(T obj)
{
try
{
MemoryStream stream = new MemoryStream();
XmlSerializer xmlSer = new XmlSerializer(typeof(T));
xmlSer.Serialize(stream, obj);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
return sr.ReadToEnd();
}
catch (Exception ex)
{
throw new Exception("将实体对象转换成XML异常", ex);
}
}
///
/// 将XML转换成实体对象
///
/// 实体类型
/// XML
public static T ToClass(string strXML) where T : class
{
try
{
using StringReader sr = new StringReader(strXML);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
catch (Exception ex)
{
throw new Exception("将XML转换成实体对象异常", ex);
}
}
}
}