Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
In memory xml serializer utility
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