7

Hi I am trying to serialize

FileStream fileStream = new FileStream("batches.xml", FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>));
List<Batche> listOfBatches = new List<Batche>();

[Serializable]
[XmlRoot("Batch")]
public class Batche
{   

    [XmlElement("Title")]
    public string Title
    {
        get;set;
    }

    [XmlArray("ListOfLinks"),XmlArrayItem("Link",Type = typeof(Link))]
    public List<Link> Links
    {
        get;set;
    }
}

[Serializable]
[XmlRoot("Link")]
public class Link
{
   [XmlElement("Uri")]
   public Uri Uri
   {
       get;
       set;
   }

   [XmlElement("Status")]
   public string Status
   {
       get;
       set;
   }

}

Getting following error : There was an error reflecting type 'System.Collections.Generic.List`1[DownloadTRON.Entities.Batche]'.

been trying this since last 4 hours, can any body point out what i am doing Wrong !

Regards Pravin

TrueWill
  • 25,132
  • 10
  • 101
  • 150
Pravin
  • 810
  • 1
  • 10
  • 17
  • This might help http://stackoverflow.com/questions/1212742/xml-serialize-generic-list-of-serializable-objects – btlog Jan 22 '11 at 16:14

3 Answers3

5

There is no problem with your code or the serialization of generics. Uri doesn't have a default constructor and cannot be serialized. Consider changing it to a string and things will work. If you are only planning on using the XmlSerializer you can remove the Serializable attribute because it isn't used.

When I ran your code with the debugger and saw the exception there was an inner exception with an inner exception with an inner exception and so on. Always a good idea to follow that rabbit down the hole when you can.

Ryan Pedersen
  • 3,177
  • 27
  • 39
3

You have to pass extra types that are in xml,to XmlSerializer, in your case Link type. Use this

XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>), new Type[] {typeof(Link)});
Vijay Sirigiri
  • 4,653
  • 29
  • 31
  • Copied and pasted this code into my test program and it gives me an InvalidOperationException. Following the chain of inner exceptions the root of the issue is still the Uri without a default constructor. – Ryan Pedersen Jan 22 '11 at 16:32
  • Yes right, I was about to add that myself. He should replace Uri with a String. And also have to specify all the extra types that are being deserialized apart from the Batches (in the XmlSerializer ctor). – Vijay Sirigiri Jan 22 '11 at 16:35
2

Your own classes must implement a public constructor with no params, for example for class Link you must implement an additional constructor

public Link() {}

Ahmad Mushtaq
  • 1,395
  • 1
  • 10
  • 32