Created
October 26, 2011 21:06
-
-
Save danieleli/1317851 to your computer and use it in GitHub Desktop.
In memory xml serializer utility
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.Xml.Serialization; | |
using System.IO; | |
using System; | |
namespace SoftwareSingularity.Utility | |
{ | |
public class XmlMemorySerializer | |
{ | |
// TODO: Make this a generic class <T> | |
private const string NAMESPACE_PREFIX = "examplews"; | |
private const string NAMESPACE = "https://services.example.com"; | |
public static string Serialize(object obj) | |
{ | |
var xmlString = string.Empty; | |
using (var stream = new MemoryStream()) | |
{ | |
xmlString = ReadStream(obj, stream); | |
} | |
return xmlString; | |
} | |
private static string ReadStream(object obj, MemoryStream stream) | |
{ | |
string xmlString; | |
InitializeStream(obj, stream); | |
using (var reader = new StreamReader(stream)) | |
{ | |
xmlString = reader.ReadToEnd(); | |
} | |
return xmlString; | |
} | |
private static void InitializeStream(object obj, MemoryStream stream) | |
{ | |
var namespaces = new XmlSerializerNamespaces(); | |
namespaces.Add(NAMESPACE_PREFIX, NAMESPACE); | |
var serializer = new XmlSerializer(obj.GetType()); | |
serializer.Serialize(stream, obj, namespaces); | |
stream.Seek(0, SeekOrigin.Begin); | |
} | |
public static T DeserializeXml<T>(string xmlString) | |
{ | |
var xmlSerializer = new XmlSerializer(typeof(T)); | |
var encoding = new System.Text.UTF8Encoding(); | |
var bytes = encoding.GetBytes(xmlString); | |
var stream = new MemoryStream(bytes); | |
var returnObj = (T)xmlSerializer.Deserialize(stream); | |
return returnObj; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment