using System.Text; using System.Xml.Serialization; namespace DynamicBible.DataPreparation.Models; public static class XML { public static bool SaveData(object o, string path) { File.WriteAllText(path, Serialize(o)); return true; } public static bool SaveData(object o) { return SaveData(o, o.GetType().Name + ".xml"); } public static T? GetData(string path, EncodingType enc = EncodingType.ASCII) { return Deserialize(File.ReadAllText(path), enc); } private static string Serialize(object o) { var serializer = new XmlSerializer(o.GetType()); var ms = new MemoryStream(); serializer.Serialize(ms, o); return Encoding.UTF8.GetString(ms.ToArray()); } private static T? Deserialize(string s, EncodingType enc = EncodingType.ASCII) { // the xmlserializer throws and handles an exception. this is normal behavior. microsoft doesn't plan to fix this. // http://stackoverflow.com/questions/1127431/xmlserializer-giving-filenotfoundexception-at-constructor var deserializer = new XmlSerializer(typeof(T)); byte[] byteArray; if (enc == EncodingType.ASCII) { byteArray = Encoding.ASCII.GetBytes(s); } else { byteArray = Encoding.UTF8.GetBytes(s); } var stream = new MemoryStream(byteArray); return (T?)deserializer.Deserialize(stream); } } public enum EncodingType { ASCII, UTF8, }