【问题标题】:Nested List Item reflecting type error嵌套列表项反映类型错误
【发布时间】:2016-02-29 18:44:43
【问题描述】:

我有一个模型,其中包含变量和另一个类实例的列表.. 这里的模型:

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

如果我从 List 中删除 'exam=examsLocal' 变量,该行会抛出异常工作正常。

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

【问题讨论】:

    标签: wpf xml-serialization


    【解决方案1】:

    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类中的属性声明:

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

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 2011-12-23
      • 2012-04-14
      • 1970-01-01
      • 2013-04-05
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多