Created
February 26, 2013 06:26
-
-
Save wahidshalaly/5036353 to your computer and use it in GitHub Desktop.
Simply, XML Custom 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
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