> I was wondering if it possible for an object to serialize/deserialize
itself from XML.
I must be misunderstanding the original question, because I use this pattern
in some of the apps I have written.
In my typical scenario, an object has
- a static ReadFromXml() method (or you could call it Deserialize if you
want) which returns an instance of the object. IT's something like a
factory. It accepts an XML file, a stream, or whatever you want to
deserialize from.
- an instance method called Save() which serializes. There might be
multiple Save() methods that serialize to different sinks.
Within these methods, you'll use an XmlSerializer to do the serialization
and de-serialization.
> I'd be guessing that it would need to use the XmlSerializer class, but
that seems to want to create a brand new object when deserializing.
When de-serializing, yes, you create a brand new object. This is why the
ReadFromXml is a static method. How can an object instance de-serialize
itself if the instance already exists? In the pattern I have used, the TYPE
can de-serialize itself, but an object instance cannot de-serialize itself
(I think by definition).
> In my case I have an existing object that I'd like to pass some XML to for
the object to repopulate its member variables. Similarly I'd like it to be
able to populate an XML string from the values of its member variables. The
member variables will be primitive types, plus possibly DateTime values (not
sure if that's classed as a primitive type).
As some body else suggested, maybe you should just fake it. An instance
method called "RefreshFromXml' might de-serialize a new instance, and then
copy values from the new instance to "this".
-D
"John Q" <(E-Mail Removed)> wrote in message
news:028AE03E-730E-40F8-AB6D-(E-Mail Removed)...
> Deserialization always creates a new object, but that doesn't mean you
can't fake it. I'd use an XmlSerializer, but instead of serializing the
entire object, I'd serialize a private member variable called "State" or
sumsuch that is a shallow copy of the object. Then, just sync the object
with the State variable upon deserialization.
>
> That way, it all happens internally and outside viewers of your class
would never realize a new object was created.
|