using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; namespace SabreTools.Serialization { /// /// XML serializer for nullable types /// public abstract partial class XmlSerializer { /// /// Serializes the defined type to an XML file /// /// Data to serialize /// Path to the file to serialize to /// Data to serialize /// True on successful serialization, false otherwise public static bool SerializeToFile(T? obj, string path) => SerializeToFile(obj, path, null, null, null, null); /// /// Serializes the defined type to an XML file /// /// Data to serialize /// Path to the file to serialize to /// Data to serialize /// Optional DOCTYPE name /// Optional DOCTYPE pubid /// Optional DOCTYPE sysid /// Optional DOCTYPE name /// True on successful serialization, false otherwise protected static bool SerializeToFile(T? obj, string path, string? name = null, string? pubid = null, string? sysid = null, string? subset = null) { using var stream = SerializeToStream(obj, name, pubid, sysid, subset); if (stream == null) return false; using var fs = File.OpenWrite(path); stream.CopyTo(fs); return true; } /// /// Serializes the defined type to a stream /// /// Data to serialize /// Stream containing serialized data on success, null otherwise public static Stream? SerializeToStream(T? obj) => SerializeToStream(obj, null, null, null, null); /// /// Serializes the defined type to a stream /// /// Data to serialize /// Optional DOCTYPE name /// Optional DOCTYPE pubid /// Optional DOCTYPE sysid /// Optional DOCTYPE name /// Stream containing serialized data on success, null otherwise protected static Stream? SerializeToStream(T? obj, string? name = null, string? pubid = null, string? sysid = null, string? subset = null) { // If the object is null if (obj == null) return null; // Setup the serializer and the reader var serializer = new XmlSerializer(typeof(T)); var settings = new XmlWriterSettings { CheckCharacters = false, Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t", NewLineChars = "\n", }; var stream = new MemoryStream(); var streamWriter = new StreamWriter(stream); var xmlWriter = XmlWriter.Create(streamWriter, settings); // Write the doctype if provided if (!string.IsNullOrWhiteSpace(name)) xmlWriter.WriteDocType(name, pubid, sysid, subset); // Perform the deserialization and return serializer.Serialize(xmlWriter, obj); stream.Seek(0, SeekOrigin.Begin); return stream; } } }