2023-07-28 10:28:44 -04:00
|
|
|
using System.IO;
|
|
|
|
|
using System.Xml;
|
|
|
|
|
using System.Xml.Serialization;
|
|
|
|
|
|
|
|
|
|
namespace SabreTools.Serialization
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// XML deserializer for nullable types
|
|
|
|
|
/// </summary>
|
|
|
|
|
public abstract partial class XmlSerializer<T>
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Deserializes an XML file to the defined type
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="path">Path to the file to deserialize</param>
|
|
|
|
|
/// <returns>Deserialized data on success, null on failure</returns>
|
|
|
|
|
public static T? Deserialize(string path)
|
|
|
|
|
{
|
2023-07-30 09:00:15 -04:00
|
|
|
using var stream = PathProcessor.OpenStream(path);
|
|
|
|
|
return Deserialize(stream);
|
2023-07-28 10:28:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Deserializes an XML file in a stream to the defined type
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="stream">Stream to deserialize</param>
|
|
|
|
|
/// <returns>Deserialized data on success, null on failure</returns>
|
|
|
|
|
public static T? Deserialize(Stream? stream)
|
|
|
|
|
{
|
2023-07-30 09:00:15 -04:00
|
|
|
// If the stream is null
|
|
|
|
|
if (stream == null)
|
|
|
|
|
return default;
|
2023-07-28 10:28:44 -04:00
|
|
|
|
2023-07-30 09:00:15 -04:00
|
|
|
// Setup the serializer and the reader
|
|
|
|
|
var serializer = new XmlSerializer(typeof(T));
|
|
|
|
|
var settings = new XmlReaderSettings
|
2023-07-28 10:28:44 -04:00
|
|
|
{
|
2023-07-30 09:00:15 -04:00
|
|
|
CheckCharacters = false,
|
|
|
|
|
DtdProcessing = DtdProcessing.Ignore,
|
|
|
|
|
};
|
|
|
|
|
var streamReader = new StreamReader(stream);
|
|
|
|
|
var xmlReader = XmlReader.Create(streamReader, settings);
|
|
|
|
|
|
|
|
|
|
// Perform the deserialization and return
|
|
|
|
|
return (T?)serializer.Deserialize(xmlReader);
|
2023-07-28 10:28:44 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|