3

New to xml serialization and could not find my specific issue.

Using this code to serialize:

Human h = new Human();

XmlSerializer writer = new XmlSerializer( typeof( Human ) );

System.IO.StreamWriter file = new System.IO.StreamWriter(
  @"c:\temp\serializerExample.xml" );
writer.Serialize( file, h );
file.Close();

Get inner exception:

{"There was an error reflecting field '_foods'."}

Human:

public class Human : Mammal
{
public string Name
{
  get
  {
    return "Bob";
  }
}
public Human()
{
  this.AddFood( new Hamburger("Name") );
  this.AddFood( new Salad("Name") );
}

and Mammal where the error talked about:

  public abstract class Mammal
  {
    public List<Food> _foods = new List<Food>();

    protected void AddFood(Food food)
    {
      _foods.Add( food );
    }

    public void Eat()
    {
      foreach ( var food in _foods )
      {
        food.Eat();
      }
    }
  }

Food:

  [XmlRoot(Namespace="Food")]
  [XmlInclude(typeof(Hamburger))]
  [XmlInclude( typeof( Salad ) )]
  public abstract class Food
  {
    public string PropertyName
    {
      get;
      set;
    }
    public abstract int Calories
    {
      get;
    }
    public abstract void Eat();
    public Food()
    {
    }
    public Food( string propertyName )
    {
      PropertyName = propertyName + " food ";
    }
  }

Hamburger:

public class Hamburger : Food
  {
    public Hamburger()
    {
    }
    public Hamburger(string propertyName) :base(propertyName)
    {

    }
    public override int Calories
    {
      get
      {
        return 500;
      }
    }

    public override void Eat()
    {
      Console.WriteLine( "Eat Hamburgers" );
    }
  }

Salad:

  public class Salad : Food
  {
    public Salad(string propertyName) : base(propertyName)
    {

    }
    public override int Calories
    {
      get
      {
        return 200;
      }
    }

    public override void Eat()
    {
      Console.WriteLine( "Eat Salad" );
    }
  }
O.O
  • 11,077
  • 18
  • 94
  • 182

1 Answers1

3

I think Salad is missing a Default (Parameter-less) constructor

public class Salad : Food
  {
    public Salad (){}

    public Salad(string propertyName) : base(propertyName)
    {

    }
    public override int Calories
    {
      get
      {
        return 200;
      }
    }

    public override void Eat()
    {
      Console.WriteLine( "Eat Salad" );
    }
  }
Christian Phillips
  • 18,399
  • 8
  • 53
  • 82