开发者

Object xml deserialization issue?

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开发者_StackOverflow-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.


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 for XMLSerializer.

In order to achieve this same functionality using the XMLSerializer, you will have to implement the IXmlSerializable 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 the Parent property after an object is deserialized.

There is a good example article on CodeProject that describes how to correctly implement IXmlSerializable available here.


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 from Collection<T>) that during Add/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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜