using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace SamplePre.Common.Helper
{
///
/// XML序列化/反序列化工具类(强类型读取)
///
public static class XmlSerializerHelper
{
///
/// 从XML文件反序列化为指定类型的对象
///
/// 目标实体类型
/// XML文件路径
/// 实体对象
public static T DeserializeFromXml(string filePath) where T : class, new()
{
// 检查文件是否存在
if (!File.Exists(filePath))
{
throw new FileNotFoundException("XML配置文件不存在", filePath);
}
try
{
// 初始化序列化器
XmlSerializer serializer = new XmlSerializer(typeof(T));
// 读取文件并反序列化
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return serializer.Deserialize(fs) as T;
}
}
catch (Exception ex)
{
throw new Exception("XML反序列化失败,检查XML格式和实体类是否匹配", ex);
}
}
///
/// 将对象序列化为XML并保存到文件
///
/// 实体类型
/// 实体对象
/// 保存路径
public static void SerializeToXml(T obj, string filePath) where T : class
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj), "序列化对象不能为null");
}
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
// 写入文件(UTF8编码,避免中文乱码)
using (StreamWriter sw = new StreamWriter(filePath, false, System.Text.Encoding.UTF8))
{
serializer.Serialize(sw, obj);
}
}
catch (Exception ex)
{
throw new Exception("XML序列化失败", ex);
}
}
}
}