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?
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.
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.
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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With