views:

548

answers:

4

Lets say we have a derivided class "SerializableLabel" from the base class "System.Windows.Controls.

[XmlRoot("SerializableLabel")]
public class SerializableLabel : Label
{
    public string foo = "bar";
}

I'd like to serialize this class but ignore ALL of the properties in the parent class. Ideally the xml would look something like:

<SerializableLable>
    <foo>bar</foo>
</SerializableLable>

How is this best achieved?

My first attempt used the typical XmlSerializer approach:

XmlSerializer s = new XmlSerializer(typeof(SerializableLabel));
TextWriter w = new StreamWriter("test.xml");
s.Serialize(w, lbl);
w.Close();

But this raises an exception because the serializer attempts to serialize a base class property which is an interface (ICommand Command).

A: 

You could write a custom serializer with IXmlSerializable, but you would create a situation where your serialization does not reconstitute the class properly. Let's say someone the BackColor on your SerializableLabel, that would not come through the serialization process properly.

JP Alioto
A: 

In your text.xml file, you might want to rename the root to be SerializableLabel, not SerializableLable (small typo)

SwDevMan81
A: 

One possible root of the above problems (including the one pointed out by JP) is that your class hierarchy tries to violate the Liskov Substitution Principle. In simpler terms, the derived class tries not to do what the base class already does. In still other words, you're trying to create a derived label that is not substitutable for the base label.

The most effective remedy here may involve decoupling the two things that SerializableLabel is tries to do, (a) UI-related functions and (b) storing serializable data, and having them in different classes.

azheglov
Thanks for your answers!It does seem like I'm violating the Liskov Substitution Principle. Perhaps this is because I'm being rather zealous about ignoring properties in the base class. The truth is I only want to ignore properties that prevent serialization of the label - eg those whose type is an interface.
ccunni
+1  A: 

If you want to ignore properties during serialization, you can use Xml Attribute overrides.
See this question for an intro to attribute overrides.

Cheeso
this helped, thanks
ccunni