Created
June 9, 2016 14:19
-
-
Save vadim-kovalyov/1cfdafdafad4edcc0f5034f587760314 to your computer and use it in GitHub Desktop.
Standard helper for XML Serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Xml.Serialization; | |
namespace Common | |
{ | |
/// <summary> | |
/// XML Serialization utils. | |
/// </summary> | |
public static class XmlSerializer | |
{ | |
/// <summary> | |
/// Serializes entity to XML string. | |
/// </summary> | |
public static string SerializeToString<T>(T entity) where T : class | |
{ | |
using (Stream dataStream = SerializeToStream(entity)) | |
{ | |
return new StreamReader(dataStream).ReadToEnd(); | |
} | |
} | |
/// <summary> | |
/// Deserializes entity from XML string. | |
/// </summary> | |
public static T DeserializeFromString<T>(string data) where T : class | |
{ | |
using(var dataStream = new MemoryStream()) | |
using (var sw = new StreamWriter(dataStream)) | |
{ | |
sw.Write(data); | |
sw.Flush(); | |
dataStream.Seek(0, 0); | |
return DeserializeFromStream<T>(dataStream); | |
} | |
} | |
/// <summary> | |
/// Serializes entity to XML stream. | |
/// </summary> | |
public static Stream SerializeToStream<T>(T entity) where T : class | |
{ | |
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); | |
namespaces.Add(string.Empty, string.Empty); | |
var ser = new System.Xml.Serialization.XmlSerializer(typeof(T)); | |
var data = new MemoryStream(); | |
ser.Serialize(data, entity, namespaces); | |
data.Seek(0, 0); | |
return data; | |
} | |
/// <summary> | |
/// Deserializes entity from XML stream. | |
/// </summary> | |
public static T DeserializeFromStream<T>(Stream data) where T : class | |
{ | |
var ser = new System.Xml.Serialization.XmlSerializer(typeof(T)); | |
data.Seek(0, 0); | |
return ser.Deserialize(data) as T; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment