Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize an object to XElement and Deserialize it in memory

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?

like image 211
Arian Avatar asked Dec 04 '11 05:12

Arian


People also ask

What is XML serialization and Deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.

What does it mean to serialize XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


1 Answers

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>(); 
like image 99
Abdul Munim Avatar answered Sep 25 '22 18:09

Abdul Munim