using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Common.system
{
///
/// 通用XML序列化和反序列化工具类
/// 创建人:赵耀
/// 创建时间:2018年11月16日
///
public static class XmlUtilHelper
{
#region 反序列化
///
/// 反序列化
///
/// 类型
/// XML字符串
///
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception)
{
return null;
}
}
///
/// 反序列化
///
///
///
///
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
///
/// 反序列化实体
///
///
///
///
public static T DeSerializer(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)
{
return null;
}
}
///
/// 从xml序列中反序列化
///
///
public static object Deserailize(Type type, string filename)
{
try
{
object obj;
if (!System.IO.File.Exists(filename))
{
throw new Exception("指定文件不存在");
}
//Xml格式反序列化
using (Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
XmlSerializer formatter = new XmlSerializer(type);
obj = formatter.Deserialize(stream);
stream.Close();
}
return obj;
}
catch (Exception)
{
//Logger.Log4NetHelp.Error("反序列化失败:", e);
return null;
}
}
///
/// 将xml转为Datable
///
public static DataTable XmlToDataTable(string xmlStr)
{
if (!string.IsNullOrEmpty(xmlStr))
{
StringReader strStream = null;
XmlTextReader xmlrdr = null;
try
{
DataSet ds = new DataSet();
//读取字符串中的信息
strStream = new StringReader(xmlStr);
//获取StrStream中的数据
xmlrdr = new XmlTextReader(strStream);
//ds获取Xmlrdr中的数据
ds.ReadXml(xmlrdr);
return ds.Tables[0];
}
catch (Exception)
{
return null;
}
finally
{
//释放资源
if (xmlrdr != null)
{
xmlrdr.Close();
strStream.Close();
strStream.Dispose();
}
}
}
return null;
}
#endregion
#region 序列化
///
/// 实体类转XML
///
///
///
///
public static string XmlSerialize(T obj)
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}
///
/// 序列化
///
/// 类型
/// 对象
///
public static string Serializer(Type type, object obj)
{
MemoryStream stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化对象
xml.Serialize(stream, obj);
}
catch (InvalidOperationException)
{
//Logger.Log4NetHelp.Error("序列化失败:", ex);
}
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string str = sr.ReadToEnd();
sr.Dispose();
stream.Dispose();
return str;
}
#endregion
}
}