dc/Utilities/XmlSerializeUtil.cs

91 lines
2.7 KiB
C#
Raw Normal View History

2022-04-01 17:03:54 +08:00
#region << >>
/*----------------------------------------------------------------
* Hupe
* 2021/11/15 14:40:30
* V1.0.0
*
*
* ----------------------------------------------------------------
*
*
*
*
* V1.0.1
*----------------------------------------------------------------*/
#endregion << >>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using ARI.EAP.HOST.Common;
using System.Windows.Forms;
using Glorysoft.SECS.EQP.Utilities;
namespace ARI.EAP.HOST.Utilities
{
/// <summary>
/// <remarks>Xml序列化与反序列化</remarks>
/// <creator>Hupe</creator>
/// </summary>
public class XmlSerializeUtil
{
#region
/// <summary>
/// 反序列化
/// </summary>
/// <param name="xml">XML字符串</param>
/// <returns></returns>
public static T Deserialize<T>(string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(typeof(T));
return (T)xmldes.Deserialize(sr);
}
}
catch(Exception e)
{
MessageBox.Show(e.Message, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
LoggerService.SYSLogger.Error(e);
return default(T);
}
}
#endregion
#region xml文件并保存到本地
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj">对象</param>
/// <returns></returns>
public static void Serializer<T>(T obj)
{
try
{
using (StreamWriter sw = new StreamWriter(Constants.configuerPath, false, new UTF8Encoding(false)))
{
Type t = obj.GetType();
XmlSerializer xml = new XmlSerializer(t);
//序列化对象
xml.Serialize(sw, obj);
sw.Close();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Save(sw);
}
}
catch(Exception e)
{
MessageBox.Show(e.Message, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
LoggerService.SYSLogger.Error(e);
}
}
#endregion
}
}