I want to deserialize back my class using System.Xml.Serialization, but i’ve noticed a strange behaviour using List Properties:
it never calls the set method, which lead me to loosing vital informations …
I’d like to avoid to switch serialization method.
public class Category
{
private string _name;
private List<Category> _subCategories;
private Category _parent;
public string Name
{
get { return _name; }
set { _name = value; }
}
public List<Category> SubCategories
{
get { return _subCategories; }
set
{
_subCategories = value;
foreach (Category category in _subCategories)
{
category.Parent = this;
}
}
}
[System.Xml.Serialization.XmlIgnoreAttribute]
public Category Parent
{
get { return _parent; }
set { _parent = value; }
}
}
Actually, the serializer does set the
SubCategoriesproperty, but it sets it to an empty list, then adds items to the list. That’s why theParentproperty of the children doesn’t get set. I wrote an article some time ago about XML serialization of parent/child relationships, you can find it here.Using the solution in that article, your
Categoryclass would look like this: