Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to deserialize XmlDocument

I am looking for a clean and short way to deserialize a XmlDocument object. The closest thing I found was this but I am really wondering if there is no nicer way to do this (in .NET 4.5 or even 4.6) since I already have the XmlDocument.

So currently this looks as follows:

// aciResponse.Data is a XmlDocument
MyClass response;
using (XmlReader reader = XmlReader.Create((new StringReader(aciResponse.Data.InnerXml))))
{
    var serializer = new XmlSerializer(typeof(MyClass));
    response =  (MyClass)serializer.Deserialize(reader);
}

Thanks for any better idea!

like image 211
silent Avatar asked Feb 02 '15 17:02

silent


People also ask

What is the correct way of using XML Deserialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.

What does it mean to deserialize XML?

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.


1 Answers

If you already have a XmlDocument object than you could use XmlNodeReader

MyClass response = null;
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
using (XmlReader reader = new XmlNodeReader(aciResponse.Data))
{
    response = (MyClass)serializer.Deserialize(reader);
}
like image 183
Artem Popov Avatar answered Sep 20 '22 19:09

Artem Popov