Serialize an object to XElement and Deserialize it in memory

Arian picture Arian · Dec 4, 2011 · Viewed 45k times · Source

I want to serialize an object to XML, but I don't want to save it on the disk. I want to hold it in a XElement variable (for using with LINQ), and then Deserialize back to my object.

How can I do this?

Answer

Abdul Munim picture Abdul Munim · Dec 4, 2011

You can use these two extension methods to serialize and deserialize between XElement and your objects.

public static XElement ToXElement<T>(this object obj)
{
    using (var memoryStream = new MemoryStream())
    {
        using (TextWriter streamWriter = new StreamWriter(memoryStream))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            xmlSerializer.Serialize(streamWriter, obj);
            return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
        }
    }
}

public static T FromXElement<T>(this XElement xElement)
{
        var xmlSerializer = new XmlSerializer(typeof(T));
        return (T)xmlSerializer.Deserialize(xElement.CreateReader());
}

USAGE

XElement element = myClass.ToXElement<MyClass>();
var newMyClass = element.FromXElement<MyClass>();