XML De-serializing and Events

  • Thread starter Thread starter Charles Law
  • Start date Start date
C

Charles Law

Two questions really:

1. Can an object de-serialise itself?

I use XMLSerializer and the Deserialize method to read an XML file and
return an object of my given type. The code that does this then returns the
new object to the caller.

<code>
Dim serializer As New XmlSerializer(GetType(MyType))

fs = New FileStream(filename, FileMode.Open)

return CType(serializer.Deserialize(fs), MyType)
</code>

I would prefer to create a new object of type MyType and then call a method
of MyType to de-serialise it. Is this possible?

2. Is there an event that is raised when de-serialisation is complete?

In the above scenario, I need to perform some initialisation of the new
MyType object, but after it has been de-serialised. Is there an event that I
can handle that is raised when de-serialisation is complete, or, better
still, is there a method that I can implement in MyType that will get called
automatically?

TIA

Charles
 
Two questions really:

1. Can an object de-serialise itself?

I use XMLSerializer and the Deserialize method to read an XML file and
return an object of my given type. The code that does this then returns the
new object to the caller.

<code>
Dim serializer As New XmlSerializer(GetType(MyType))

fs = New FileStream(filename, FileMode.Open)

return CType(serializer.Deserialize(fs), MyType)
</code>

I would prefer to create a new object of type MyType and then call a method
of MyType to de-serialise it. Is this possible?

You could make a shared (static) member of MyType that will do the same
thing your code is doing:

Public Shared Function DeSer(filename as String) As MyType
Dim serializer As New XmlSerializer(GetType(MyType))
fs = New FileStream(filename, FileMode.Open)
return CType(serializer.Deserialize(fs), MyType)
End Sub

Now you can do:

dim data As MyType = MyType.DeSer("C:\abc\123.xml")
2. Is there an event that is raised when de-serialisation is complete?

In the above scenario, I need to perform some initialisation of the new
MyType object, but after it has been de-serialised. Is there an event that I
can handle that is raised when de-serialisation is complete, or, better
still, is there a method that I can implement in MyType that will get called
automatically?

I believe deserialization is synchronous so no other code will execute
until the deserialization is complete.
 
Hi Patrick

Thanks for the answers. The former is exactly the type of thing I was hoping
for.

With regard to the latter, it wasn't so much the synchronicity of the
process that was troubling me. It was the fact that a user of my class would
have to remember to call its Initialise method after de-serialising.
However, your answer to the first question obviates that as I can now make
it part of the shared method, so thanks again.

Charles
 
Back
Top