Skip to content

Instantly share code, notes, and snippets.

@wahidshalaly
Created February 26, 2013 06:26
Show Gist options
  • Save wahidshalaly/5036353 to your computer and use it in GitHub Desktop.
Save wahidshalaly/5036353 to your computer and use it in GitHub Desktop.
Simply, XML Custom Serialization.
public interface IXmlCustomSerializer
{
string Serialize<T>(T input);
T Deserialize<T>(string input);
}
public class XmlCustomSerializer : IXmlCustomSerializer
{
private XmlSerializer _serializer;
public string Serialize<T>(T input)
{
_serializer = new XmlSerializer(typeof(T));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
using (var stream = new MemoryStream())
{
var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding() };
using (var xmlWriter = XmlWriter.Create(stream, settings))
{
_serializer.Serialize(xmlWriter, input, ns);
var buffer = new byte[stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer);
}
}
}
public T Deserialize<T>(string input)
{
_serializer = new XmlSerializer(typeof(T));
using (var memoryStream = new MemoryStream())
{
byte[] buffer = Encoding.UTF8.GetBytes(input);
memoryStream.Write(buffer, 0, buffer.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
return (T)_serializer.Deserialize(memoryStream);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment