1

I have the following classes:

[XmlInclude(typeof(Cat))]
[XmlInclude(typeof(Dog))]
[XmlInclude(typeof(Cow))]
[Serializable]
public abstract class Animal
{
    public string Name { get; set; }
}

public class Cow : Animal
{
    public Cow(string name) { Name = name; }
    public Cow() { }
}

public class Dog : Animal
{
    public Dog(string name) { Name = name; }
    public Dog() { }
}

public class Cat : Animal
{
    public Cat(string name) { Name = name; }
    public Cat() {}
}

And the following code snippet:

var animalList = new List<Animal>();
Type type = AnimalTypeBuilder.CompileResultType("Elephant", propertiesList);
var elephant = Activator.CreateInstance(type);

animalList.Add(new Dog());
animalList.Add(new Cat());
animalList.Add(new Cow());
animalList.Add((Animal)elephant);

using (var writer = new System.IO.StreamWriter(fileName))
{
     var serializer = new XmlSerializer(animalList.GetType());
     serializer.Serialize(writer, animalList);
     writer.Flush();
}

When I try to serialize this list I get the error:

System.InvalidOperationException: The type Elephant was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

At first I also got this exception for Cat, Cow and Dog objects and solved it by adding [XmlInclude(typeof(...))] to their classes as seen above, but I can't find a similar solution for a dynamic derived type since this attribute is set at compile time.

steve16351
  • 5,372
  • 2
  • 16
  • 29
MaorK84
  • 11
  • 3

1 Answers1

3

You can tell the XmlSerializer about the extra types required via the constructor at run time. For example:

var serializer = new XmlSerializer(animalList.GetType(), new[] { typeof(Elephant) });
steve16351
  • 5,372
  • 2
  • 16
  • 29
  • 1
    Thanks! It worked perfectly. Only now another problem: I get an exception that elephant is an unknown type when deserializing an xml file at which type elephant was saved in at previous program run. desrialize has to get the same list of types as serialize, but how can I give it dynamic types which were created before ? – MaorK84 Aug 22 '17 at 18:24