jellyfin/MediaBrowser.Common.Implementations/Serialization/XmlSerializer.cs

96 lines
3.0 KiB
C#
Raw Normal View History

2013-02-24 21:53:54 +00:00
using MediaBrowser.Model.Serialization;
2013-02-21 01:33:05 +00:00
using System;
using System.IO;
using System.Xml;
2013-02-24 21:53:54 +00:00
namespace MediaBrowser.Common.Implementations.Serialization
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Provides a wrapper around third party xml serialization.
/// </summary>
2013-02-24 21:53:54 +00:00
public class XmlSerializer : IXmlSerializer
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Serializes to writer.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="writer">The writer.</param>
2013-02-24 21:53:54 +00:00
private void SerializeToWriter(object obj, XmlTextWriter writer)
2013-02-21 01:33:05 +00:00
{
writer.Formatting = Formatting.Indented;
var netSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
netSerializer.Serialize(writer, obj);
}
/// <summary>
/// Deserializes from stream.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="stream">The stream.</param>
/// <returns>System.Object.</returns>
2013-02-24 21:53:54 +00:00
public object DeserializeFromStream(Type type, Stream stream)
2013-02-21 01:33:05 +00:00
{
using (var reader = new XmlTextReader(stream))
{
var netSerializer = new System.Xml.Serialization.XmlSerializer(type);
return netSerializer.Deserialize(reader);
}
}
/// <summary>
/// Serializes to stream.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="stream">The stream.</param>
2013-02-24 21:53:54 +00:00
public void SerializeToStream(object obj, Stream stream)
2013-02-21 01:33:05 +00:00
{
using (var writer = new XmlTextWriter(stream, null))
{
SerializeToWriter(obj, writer);
}
}
/// <summary>
/// Serializes to file.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="file">The file.</param>
2013-02-24 21:53:54 +00:00
public void SerializeToFile(object obj, string file)
2013-02-21 01:33:05 +00:00
{
using (var stream = new FileStream(file, FileMode.Create))
{
SerializeToStream(obj, stream);
}
}
/// <summary>
/// Deserializes from file.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="file">The file.</param>
/// <returns>System.Object.</returns>
2013-02-24 21:53:54 +00:00
public object DeserializeFromFile(Type type, string file)
2013-02-21 01:33:05 +00:00
{
using (var stream = File.OpenRead(file))
{
return DeserializeFromStream(type, stream);
}
}
/// <summary>
/// Deserializes from bytes.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="buffer">The buffer.</param>
/// <returns>System.Object.</returns>
2013-02-24 21:53:54 +00:00
public object DeserializeFromBytes(Type type, byte[] buffer)
2013-02-21 01:33:05 +00:00
{
using (var stream = new MemoryStream(buffer))
{
return DeserializeFromStream(type, stream);
}
}
}
}