mirror of
https://gitlab.com/walljm/dynamicbible.git
synced 2025-07-23 15:30:14 -04:00
60 lines
1.5 KiB
C#
60 lines
1.5 KiB
C#
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<T>(string path, EncodingType enc = EncodingType.ASCII)
|
|
{
|
|
return Deserialize<T>(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<T>(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,
|
|
} |