我的XMLSerializer仅保存我保存的最后一个对象

时间:2019-07-03 19:46:51

标签: c# oop serialization xml-serialization xmlserializer

我的XML序列化器仅保存我保存的最后一个元素。它应该包含我已序列化的所有对象的列表!

    [Serializable]
    public class Teacher
    {

        public string Name { get; set; }

        public string Subject { get; set; }

        public void Save(string fileName)
        {
            using (var stream = new FileStream(@fileName, FileMode.Create))
            {
                var XML = new XmlSerializer(typeof(Teacher));
                XML.Serialize(stream, this);
            }
        }

        public static Teacher Load(string fileName)
        {
            using (var stream = new FileStream(@fileName, FileMode.Open))
            {
                var XML = new XmlSerializer(typeof(Teacher));
                return (Teacher)XML.Deserialize(stream);
            }
        }
    }

我一次创建一个对象,并得到以下XML以及最后的结果。

<?xml version="1.0"?>
<Teacher xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ID>0</ID>
  <Name>Samuel9</Name>
  <Subject>IDS9</Subject>
</Teacher>```

0 个答案:

没有答案