Add and convert XML base class

This commit is contained in:
Matt Nadareski
2023-09-08 17:03:31 -04:00
parent 6040b011aa
commit cf9de66a85
3 changed files with 121 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
namespace SabreTools.Serialization.Files
{
/// <summary>
/// Base class for other XML serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class XmlFile<T> : IFileSerializer<T>
{
/// <inheritdoc/>
#if NET48
public T Deserialize(string path)
#else
public T? Deserialize(string? path)
#endif
{
using (var data = PathProcessor.OpenStream(path))
{
return new Streams.XmlFile<T>().Deserialize(data);
}
}
}
}

54
PathProcessor.cs Normal file
View File

@@ -0,0 +1,54 @@
using System;
using System.IO;
using System.IO.Compression;
namespace SabreTools.Serialization
{
internal class PathProcessor
{
/// <summary>
/// Opens a path as a stream in a safe manner, decompressing if needed
/// </summary>
/// <param name="path">Path to open as a stream</param>
/// <returns>Stream representing the file, null on error</returns>
#if NET48
public static Stream OpenStream(string path)
#else
public static Stream? OpenStream(string path)
#endif
{
try
{
// If we don't have a file
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return null;
// Open the file for deserialization
var stream = File.OpenRead(path);
// Get the extension to determine if additional handling is needed
string ext = Path.GetExtension(path).TrimStart('.');
// Determine what we do based on the extension
if (string.Equals(ext, "gz", StringComparison.OrdinalIgnoreCase))
{
return new GZipStream(stream, CompressionMode.Decompress);
}
else if (string.Equals(ext, "zip", StringComparison.OrdinalIgnoreCase))
{
// TODO: Support zip-compressed files
return null;
}
else
{
return stream;
}
}
catch
{
// TODO: Handle logging the exception
return null;
}
}
}
}

View File

@@ -0,0 +1,45 @@
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace SabreTools.Serialization.Streams
{
/// <summary>
/// Base class for other XML serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class XmlFile<T> : IStreamSerializer<T>
{
/// <inheritdoc/>
#if NET48
public T Deserialize(Stream data)
#else
public T? Deserialize(Stream? data)
#endif
{
// If the stream is null
if (data == null)
return default;
// Setup the serializer and the reader
var serializer = new XmlSerializer(typeof(T));
var settings = new XmlReaderSettings
{
CheckCharacters = false,
DtdProcessing = DtdProcessing.Ignore,
ValidationFlags = XmlSchemaValidationFlags.None,
ValidationType = ValidationType.None,
};
var streamReader = new StreamReader(data);
var xmlReader = XmlReader.Create(streamReader, settings);
// Perform the deserialization and return
#if NET48
return (T)serializer.Deserialize(xmlReader);
#else
return (T?)serializer.Deserialize(xmlReader);
#endif
}
}
}