-
Xml serialization
Hi,
I am trying to hind a public property of a base class from the serialization of the derived class. But it does not work. Where is my mistake?
Code:
[XmlRoot("Components")
public class Component
{
private List<Part> _parts = new List<Part>();
[XmlElement("Parts")]
public virtual List<Part> Parts
{
get { return _parts; }
set { _parts = value; }
}
}
[XmlRoot("Other_Components")]
public class ComponentA : Component
{
[XmlIgnore]
public override List<Part> Parts
{
get { return base.Parts; }
set { base.Parts = value; }
}
}
If I serialize ComponentA I do not want serialize Parts. But this code fails. Any hints?
-
Re: Xml serialization
I guess the [XmlElement] attribute is inherited by Parts in ComponentA. I suggest you try to declare Parts in ComponentA as new, not an override.
-
Re: Xml serialization
It is a MISTAKE to try to do this. It violates the IS-A policy. You should consider aggregation rather than inheritance.
-
Re: Xml serialization
@cilu: Your hint did not work too.
@TheCPUWizard: I know that my design is not very well. But I did not found any good approach for my problem. I will try to explain my problem. Maybe you can show me the right direction.
I have to design the following behavior and get this kinds of xml fragments:
Code:
<component hasPart="true">
<parts>
<part color="red" id="1" />
<part color="blue" id="2" />
</parts>
<component>
or
<component hasParts="false" color="red" id="1" />
To engage the problem I have created my class Component for the internal usage. If I get a component fragment without a part I will put regardless one instance of part into the parts collection. Inside of that part I store the properties for the component. If I get a component with parts I store each part into the parts collection as usual.
The ComponentA class I use at the moment only to serialize the object in the right structure. I do not want to serialize each property manually.
I am not happy with this approach but how I said I did not found a better one for the moment. A good advice is very welcomed.
-
Re: Xml serialization
No need for anything fancy. Jusr check for an empty collection AFTER deserialization, and put in your instance.....