using System; using System.IO; using System.Xml.Serialization; public static class XmlStorage { /// /// 序列化对象到XML文件 /// /// /// /// /// public static void SerializeToXml(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); } } /// /// 从XML文件反序列化对象 /// /// /// /// /// public static T DeserializeFromXml(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); } } }