title: XML serialization of List<Object>
body: <p>I am failing to save a list of Animals to disk with XML serialization.</p>
  
  <p>I am getting Exception:Thrown: "The type AnimalLibrary.Animals.Mammals.Dog was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically." (System.InvalidOperationException)</p>
  
  <p>If I try the commented code with the "Dog" it will work just as expected and the XML is generated. But the same dog sent in as the only element in the List does not work.</p>
  
  <pre><code>    [XmlElement("animalList")]
      public List&lt;Animal&gt; animalList = new List&lt;Animal&gt;();
  
  public bool SaveBinary(string fileName)
      {
          Mammals.Dog dog = (Mammals.Dog)animalList[0];
  
          //IObjectSerializer&lt;Mammals.Dog&gt; obj = new XMLObjectSerializer&lt;Mammals.Dog&gt;();
          IObjectSerializer&lt;List&lt;Animal&gt;&gt; obj = new XMLObjectSerializer&lt;List&lt;Animal&gt;&gt;();
  
          bool saved = obj.SaveFile(fileName, animalList);
          if (saved)
              return true;
  
          return false;
      }
  </code></pre>
  
  <p>XML serializer</p>
  
  <pre><code>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;
      }
  </code></pre>
  
  <p>Files for inheritance of the dog. There are no xml tags inside the classes.</p>
  
  <pre><code>[XmlRoot(ElementName="Animal")]
  public abstract class Animal : IAnimal
  {
  
      /// &lt;summary&gt;
      /// Id of animal
      /// &lt;/summary&gt;
      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
  {
  
      /// &lt;summary&gt;
      /// Constructor - Create an instance of a Dog
      /// &lt;/summary&gt;
      public Dog()
      {
      }
  ........
  </code></pre>