ccunni
ccunni

Reputation: 135

.net XmlSerializer, ignore base class properties

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).

Upvotes: 3

Views: 5840

Answers (4)

Cheeso
Cheeso

Reputation: 192477

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

Upvotes: 1

azheglov
azheglov

Reputation: 5523

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.

Upvotes: 1

SwDevMan81
SwDevMan81

Reputation: 49978

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

Upvotes: 0

JP Alioto
JP Alioto

Reputation: 45117

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.

Upvotes: 0

Related Questions