Deserialize method that "loads" the class instance itself: how???

B

Bob Rock

Hello,

I've got an xml stream that I'd need to deserialize into an instance of a
given class A. I'd like to create an instance method on class A (method
Deserialize) that takes this XML stream as input and deserializes it "into
itself" ... in other words I'd like it to "fill" the instance of class A on
which the method has been called instead of returning another instance of
class A.

The code below gives a good idea of what I'd like:

public class A
{
public void Deserialize(MemoryStream stream)
{
XmlSerializer serializer = new XmlSerializer(typeof(A));

// the following line of code obviously does not work since this is
readonly
// but it gives a good idea of what I'd like to do
this = serializer.Deserialize(stream);
}
}

How can I accomplish this without having to manually "load" all the class
fields???


Bob Rock
 
D

Dennis Myrén

I would implement a static method in the class that is serializable, like:

public static YourClass Deserialize ( Stream fromStream )
{
XmlSerializer serializer = new XmlSerializer(typeof(YourClass));
return (YourClass) serializer.Deserialize(stream);
}
 
B

Bob Rock

Dennis Myrén said:
I would implement a static method in the class that is serializable, like:

public static YourClass Deserialize ( Stream fromStream )
{
XmlSerializer serializer = new XmlSerializer(typeof(YourClass));
return (YourClass) serializer.Deserialize(stream);
}

Dannis, that is what I will do if I can't find an easy way to do it with an
instance method.

Bob Rock
 
D

Dennis Myrén

Well, you can do it with an instance method by deserializing the XML
to a new instance of the class, and than copy all properties of that
instance to your actual instance, like;

public void LoadState ( Stream fromStream )
{
YourClass c = (YourClass) new
XmlSerializer(typeof(YourClass)).Deserialize(stream);
this.aProperty = c.aProperty;
this.someOtherProperty = c.someOtherProperty;
c = null;
}

Regards, Dennis
 
N

Nicholas Paldino [.NET/C# MVP]

Bob,

Why not do this. Get the schema for the XML and then run the XSD.exe
tool against it. This will create a C# file which is a class (which might
derive from DataSet if you say so) that you can compile in your app. Then,
you can use the ReadXml method on the DataSet (if you choose to have your
class derive from that), or the Deserialize method on the XmlSerializer
class to deserialize an instance of the class in your app.

Once you have that, you can do anything you want with the class, or have
a containing class use it for whatever purposes you wish.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top