Domanda

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();
È stato utile?

Soluzione

  • 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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top