using System;
using System.IO;
using System.Xml.Serialization;

public static class XmlStorage
{
    /// <summary>
    /// 序列化对象到XML文件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <param name="filePath"></param>
    /// <exception cref="InvalidOperationException"></exception>
    public static void SerializeToXml<T>(T data, string filePath)
    {
        try
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var writer = new StreamWriter(filePath))
            {
                serializer.Serialize(writer, data);
            }
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("XML serialization failed", ex);
        }
    }

    /// <summary>
    /// 从XML文件反序列化对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="filePath"></param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    public static T DeserializeFromXml<T>(string filePath)
    {
        try
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var reader = new StreamReader(filePath))
            {
                return (T)serializer.Deserialize(reader);
            }
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("XML deserialization failed", ex);
        }
    }
}