using MediaBrowser.Model.Serialization; using System; using System.IO; using System.Xml; namespace MediaBrowser.Common.Implementations.Serialization { /// /// Provides a wrapper around third party xml serialization. /// public class XmlSerializer : IXmlSerializer { /// /// Serializes to writer. /// /// The obj. /// The writer. private void SerializeToWriter(object obj, XmlTextWriter writer) { writer.Formatting = Formatting.Indented; var netSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); netSerializer.Serialize(writer, obj); } /// /// Deserializes from stream. /// /// /// The stream. /// ``0. public T DeserializeFromStream(Stream stream) { using (var reader = new XmlTextReader(stream)) { var netSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); return (T)netSerializer.Deserialize(reader); } } /// /// Deserializes from stream. /// /// The type. /// The stream. /// System.Object. public object DeserializeFromStream(Type type, Stream stream) { using (var reader = new XmlTextReader(stream)) { var netSerializer = new System.Xml.Serialization.XmlSerializer(type); return netSerializer.Deserialize(reader); } } /// /// Serializes to stream. /// /// The obj. /// The stream. public void SerializeToStream(object obj, Stream stream) { using (var writer = new XmlTextWriter(stream, null)) { SerializeToWriter(obj, writer); } } /// /// Deserializes from file. /// /// /// The file. /// ``0. public T DeserializeFromFile(string file) { using (var stream = File.OpenRead(file)) { return DeserializeFromStream(stream); } } /// /// Serializes to file. /// /// The obj. /// The file. public void SerializeToFile(object obj, string file) { using (var stream = new FileStream(file, FileMode.Create)) { SerializeToStream(obj, stream); } } /// /// Deserializes from file. /// /// The type. /// The file. /// System.Object. public object DeserializeFromFile(Type type, string file) { using (var stream = File.OpenRead(file)) { return DeserializeFromStream(type, stream); } } /// /// Deserializes from bytes. /// /// The type. /// The buffer. /// System.Object. public object DeserializeFromBytes(Type type, byte[] buffer) { using (var stream = new MemoryStream(buffer)) { return DeserializeFromStream(type, stream); } } /// /// Serializes to bytes. /// /// The obj. /// System.Byte[][]. public byte[] SerializeToBytes(object obj) { using (var stream = new MemoryStream()) { SerializeToStream(obj, stream); return stream.ToArray(); } } } }