简体   繁体   English

类未序列化到XML文件

[英]Class not serializing to XML File

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();
  • 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 XmlSerializer不会序列化抽象属性,请考虑到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM