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; } /// /// 实体类转XML /// /// /// /// public static string XmlSerialize(T obj) { using (StringWriter sw = new StringWriter()) { Type t = obj.GetType(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(sw, obj); sw.Close(); return sw.ToString(); } } #endregion #region 序列化 /// /// 序列化 /// /// 类型 /// 对象 /// 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 } }