I am having huge problems with XML serialization. I have two classes, both need to be serializeable. In the inherited class, I would like to change the serialization behavio
You're specifying two different XML elements with the same name on the same graph level, which is not allowed.
I will offer a solution, but it involves concatenating type and name for the Cat class serialization. If it is not imperative to serialize that NameAndType class, then go on: On Animal, set Name to be virtual; On Cat, set XmlIgnore on Name2. Then override Name and return both properties of Name2 the way you fancy.
If you really need to serialize that class as it is, then I'm afraid you'll have to so it with a different elementName.
Edit: Sample code:
public class Animal
{
[XmlElement(ElementName = "NAME")]
public virtual string Name { get; set; }
public virtual bool ShouldSerializeName() { return true; }
}
public class Cat : Animal
{
public override bool ShouldSerializeName() { return false; }
[XmlIgnore]
public NameAndType Name2 { get; set; }
[XmlElement(ElementName = "NAME")]
public override string Name
{
get
{
return String.Format("{0} [Type:{1}]", Name2.Name, Name2.Type);
}
set { }
}
}