Serialize an object to XElement and Deserialize it in memory

C#XmlLinqSerializationC# 4.0

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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>();

Solution 2 - C#

You can use XMLSerialization

> XML serialization is the process of converting an object's public > properties and fields to a serial format (in this case, XML) for > storage or transport. Deserialization re-creates the object in its > original state from the XML output. You can think of serialization as > a way of saving the state of an object into a stream or buffer. For > example, ASP.NET uses the XmlSerializer class to encode XML Web > service messages

and XDocument Represents an XML document to achieve this

   using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;


namespace ConsoleApplication5
{
  public class Person
  {
    public int Age { get; set; }
    public string Name { get; set; }
  }

  class Program
  {
    static void Main(string[] args)
    {

      XmlSerializer xs = new XmlSerializer(typeof(Person));

      Person p = new Person();
      p.Age = 35;
      p.Name = "Arnold";

      Console.WriteLine("\n Before serializing...\n");
      Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age,p.Name));

      XDocument d = new XDocument();
      using (XmlWriter xw = d.CreateWriter())
        xs.Serialize(xw, p);

      // you can use LINQ on elm now

      XElement elm = d.Root;

      Console.WriteLine("\n From XElement...\n");

      elm.Elements().All(e => { Console.WriteLine(string.Format("element name {0} , element value {1}", e.Name, e.Value)); return true; });

      //deserialize back to object
      Person pDeserialized = xs.Deserialize((d.CreateReader())) as Person;

      Console.WriteLine("\n After deserializing...\n");
      Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age, p.Name));

      Console.ReadLine();

    }
  }


}

and here is output enter image description here

Solution 3 - C#

(Late answer)

Serialize:

var doc = new XDocument();
var xmlSerializer = new XmlSerializer(typeof(MyClass));
using (var writer = doc.CreateWriter())
{
    xmlSerializer.Serialize(writer, obj);
}
// now you can use `doc`(XDocument) or `doc.Root` (XElement)

Deserialize:

MyClass obj; 
using(var reader = doc.CreateReader())
{
    obj = (MyClass)xmlSerializer.Deserialize(reader);
}

Solution 4 - C#

ToXelement without Code Analysis issues, same answer as Abdul Munim but fixed the CA issues (except for CA1004, this cannot be resolved in this case and is by design)

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

Solution 5 - C#

What about

public static byte[] BinarySerialize(Object obj)
        {
            byte[] serializedObject;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter b = new BinaryFormatter();
            try
            {
                b.Serialize(ms, obj);
                ms.Seek(0, 0);
                serializedObject = ms.ToArray();
                ms.Close();
                return serializedObject;
            }
            catch
            {
                throw new SerializationException("Failed to serialize. Reason: ");
            }

        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArianView Question on Stackoverflow
Solution 1 - C#Abdul MunimView Answer on Stackoverflow
Solution 2 - C#Surjit SamraView Answer on Stackoverflow
Solution 3 - C#Eren ErsönmezView Answer on Stackoverflow
Solution 4 - C#MartijnView Answer on Stackoverflow
Solution 5 - C#EsiView Answer on Stackoverflow