My objects has a parent-child relationship. Each child object has a Parent property pointing to its container. When this object is created in the app, it's set, and thus no problem. This Parent property is marked with XmlIgnore attribute, because it needs to be set to its run-time parent instance. So, what's the best way to initialize this Parent property after the object is deserialized? Is there a 'Deserialize completed' event or something similar?
EDIT: I'm talking about XmlSerializer in C# WPF. I don't want binary serializer.
XmlSerializer
does not provide serialization callbacks, I'm afraid. One way to do this is for the parent to handle this when adding - but you will need a custom collection (perhaps inherited fromCollection<T>
) that duringAdd
/Remove
calls some method on the child to add (or remove, if removing from the collection) the parent.Alternatively - consider simply making it a one-way only tree - i.e. the child doesn't have a parent property.
Another option is simply to walk the model through code after deserialization, and fixup any parent values.
The final option is to implement
IXmlSerializable
, but that is very hard get right.Your question is somewhat lacking in details, but from some of the attributes and properties that you describe, I'm going to assume that you're using the
XMLSerializer
in the .NET Framework.You may know about the
OnDeserialized
attribute, which you can use to mark a particular method that you want to be called after an object has been deserialized. Unfortunately, this only works with the Binary, SOAP, and DataAttribute formatters, not forXMLSerializer
.In order to achieve this same functionality using the
XMLSerializer
, you will have to implement theIXmlSerializable
interface yourself on the class that you want to serialize to XML. This will allow you to complete control over how instances of your class are serialized and deserialized, including code that is run to initialize theParent
property after an object is deserialized.There is a good example article on CodeProject that describes how to correctly implement
IXmlSerializable
available here.