嵌套列表项反映类型错误

时间:2016-02-29 18:44:43

标签: wpf xml-serialization

我有一个包含变量的模型和另一个类实例的列表。 这里的型号:

public class patient
    {
        [XmlElement("firstname")]    
        public string name { get; set; }
        [XmlElement("lastname")] 
        public string surname { get; set; }
        [XmlElement("age")]
        public int age { get; set; }
        [XmlElement("gender")] 
        public string gender { get; set; }
        [XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exam")]
        public List<exam> exam { get; set; }

    }
    public class exam
    {
        [XmlElement("id")]
        public string id { get; set; }
        [XmlElement(ElementName = "date", DataType = "DateTime")]
        public DateTime date { get; set; }
        [XmlElement("comment")] 
        public string comment { get; set; }
    }







List<exam> examsLocal = new List<exam>(){ 
                new exam{ id = "id of patient 1",  date = DateTime.Now,  comment = "coomment exam1" },
            };
        List<patient> overview = new List<patient>();
        try
        {
            var b = new List<patient>()
            { 
                new patient{ name = "name of patient 1", surname = "surname of patient 1", gender = "Female", age = 31, exam=examsLocal },
            };
            var writer = new System.Xml.Serialization.XmlSerializer(typeof(List<patient>));//throw exception

如果我删除&#39; exam = examsLocal&#39;该行会抛出异常正常工作来自List ..

的变量

序列化嵌套列表项的正确方法是什么

1 个答案:

答案 0 :(得分:0)

更新exam的班级定义,如下所示: 删除Date属性的DataType,因为Xml序列化中不允许使用System.DateTime:

public class exam
{
  [XmlElement("id")]
  public string id { get; set; }
  [XmlElement(ElementName = "date")]
  public DateTime date { get; set; }
  [XmlElement("comment")]
  public string comment { get; set; }
}

并更新patiant类中的Property声明:

 [XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exams")]
    public List<exam> exams { get; set; }