I have class Animal and classes Dog and Cat inheriting from it. Class Animal has property X. I would like to generate XML for "Dog" without "X" property and for "Cat" with "X" property. XmlIgnore doesn't work here in the way I expected.
I tried to use virtual property and then override it in derived class but it didn't work.
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Cat cat = new Cat();
SerializeToFile(dog, "testDog.xml");
SerializeToFile(cat, "testCat.xml");
}
private static void SerializeToFile(Animal animal, string outputFileName)
{
XmlSerializer serializer = new XmlSerializer(animal.GetType());
TextWriter writer = new StreamWriter(outputFileName);
serializer.Serialize(writer, animal);
writer.Close();
}
}
public abstract class Animal
{
public virtual int X { get; set; }
}
public class Dog : Animal
{
[XmlIgnore]
public override int X { get; set; }
}
public class Cat : Animal
{
public override int X { get; set; }
}