XML Serialization List <Object>

I cannot save the Animals list to an XML serialized disk.

I get an exception: selected: "The type AnimalLibrary.Animals.Mammals.Dog was not expected. Use the XmlInclude or SoapInclude attribute to indicate types that are not statically known." (System.InvalidOperationException)

If I try the commented code with "Dog", it will work as expected, and XML is generated. But the same dog sent as the only item on the list does not work.

[XmlElement("animalList")] public List<Animal> animalList = new List<Animal>(); public bool SaveBinary(string fileName) { Mammals.Dog dog = (Mammals.Dog)animalList[0]; //IObjectSerializer<Mammals.Dog> obj = new XMLObjectSerializer<Mammals.Dog>(); IObjectSerializer<List<Animal>> obj = new XMLObjectSerializer<List<Animal>>(); bool saved = obj.SaveFile(fileName, animalList); if (saved) return true; return false; } 

XML serializer

 public bool SaveFile(string fileName, T objectToSerialize) { try { //Will overwrite old file XmlSerializer mySerializer = new XmlSerializer(typeof(T)); StreamWriter myWriter = new StreamWriter(fileName); mySerializer.Serialize(myWriter, objectToSerialize); myWriter.Close(); } catch (IOException ex) { Console.WriteLine("IO Exception ", ex.Message); return false; } return true; } 

Files for dog inheritance. There are no xml tags inside the classes.

 [XmlRoot(ElementName="Animal")] public abstract class Animal : IAnimal { /// <summary> /// Id of animal /// </summary> private string id; public string ID ........ [XmlRoot(ElementName = "Animals")] public abstract class Mammal : Animal { public int NumberofTeeth { get; set; } ........ [XmlRoot(ElementName="Dog")] public class Dog : Mammal { /// <summary> /// Constructor - Create an instance of a Dog /// </summary> public Dog() { } ........ 
+6
source share
1 answer

If you want to have a list of objects and serialize them as a list of the base type, you need to tell the serializer which types of specific types are possible.

So, if you want to put the Dog and Cat object in your Animal list, you need to add markup to the Animal class as follows

 [XmlInclude(typeof(Cat))] [XmlInclude(typeof(Dog))] [XmlRoot(ElementName="Animal")] public abstract class Animal : IAnimal 
+12
source

Source: https://habr.com/ru/post/956541/


All Articles