您可以使用以下内容:
/// <summary> /// Serializes an object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serializableObject"></param> /// <param name="fileName"></param> public void SerializeObject<T>(T serializableObject, string fileName) { if (serializableObject == null) { return; } try { Xmldocument xmldocument = new Xmldocument(); XmlSerializer serializer = new XmlSerializer(serializableObject.GetType()); using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, serializableObject); stream.Position = 0; xmldocument.Load(stream); xmldocument.Save(fileName); } } catch (Exception ex) { //Log exception here } } /// <summary> /// Deserializes an xml file into an object list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"></param> /// <returns></returns> public T DeSerializeObject<T>(string fileName) { if (string.IsNullOrEmpty(fileName)) { return default(T); } T objectOut = default(T); try { Xmldocument xmldocument = new Xmldocument(); xmldocument.Load(fileName); string xmlString = xmldocument.OuterXml; using (StringReader read = new StringReader(xmlString)) { Type outType = typeof(T); XmlSerializer serializer = new XmlSerializer(outType); using (XmlReader reader = new XmlTextReader(read)) { objectOut = (T)serializer.Deserialize(reader); } } } catch (Exception ex) { //Log exception here } return objectOut; }


