Question

The code below does not output a stream. Looks correct to me but doesn't work.

LineItem i1 = new LineItem() { Id = 1, PartNumber = "abc" };
LineItem i2 = new LineItem() { Id = 2, PartNumber = "def" };
LineItem i3 = new LineItem() { Id = 3, PartNumber = "ghi" };
LineItem i4 = new LineItem() { Id = 4, PartNumber = "jkl" };

List<LineItem> l1 = new List<LineItem>();
l1.Add(i1);
l1.Add(i2);
l1.Add(i3);
l1.Add(i4);

Customer c1 = new Customer() { Id = 1, Company = "MSFT", Name = "John", LineItems = l1 };

XmlSerializer mySerializer = new XmlSerializer(typeof(Customer));
TextWriter myWriter = new StreamWriter(@"XMLFile1.xml");
mySerializer.Serialize(myWriter, c1);
myWriter.Close();
Was it helpful?

Solution

  • Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.

  • Also, remember that serialized classes must have default constructor. if you have a constructor with a parameter, you'll need to add the default one too. (having no constructors is fine)

  • XmlSerializer won't serialize abstract properties, take that into account

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top