2016-02-28 62 views
0

我想序列化的XML文件中包含的:XML序列化类型的错误

<?xml version="1.0" encoding="utf-8" ?> 
<patients> 
    <patient> 
    <firstname>Patience_name_1</firstname> 
    <lastname>Patience_surname_1</lastname> 
    <age>20</age> 
    <gender>Male</gender> 
    <exams> 
     <exam> 
     <id>1</id> 
     <date>02/27/2016</date> 
     <comment>Exam completed for patience1</comment> 
     </exam> 
    </exams> 
    </patient> 
    <patient> 
    <firstname>Patience_name_2</firstname> 
    <lastname>Patience_surname_2</lastname> 
    <age>22</age> 
    <gender>Male</gender> 
    <exams> 
     <exam> 
     <id>2</id> 
     <date>02/27/2016</date> 
     <comment>Exam completed fro patience 2</comment> 
     </exam> 
    </exams> 
    </patient> 
    <patient> 
    <firstname>Patience_name_3</firstname> 
    <lastname>Patience_surname_3</lastname> 
    <age>23</age> 
    <gender>Female</gender> 
    <exams> 
     <exam> 
     <id>3</id> 
     <date>02/26/2016</date> 
     <comment>Exam completed for patience 3</comment> 
     </exam> 
    </exams> 
    </patient> 
</patients> 

这里是我的序列化代码..我想强调与 内容时发生了点异常“是没有预料到。”错误信息

try 
    { 
     System.Xml.Serialization.XmlSerializer reader = 
       new System.Xml.Serialization.XmlSerializer(typeof(List<patient>)); 
     System.IO.StreamReader file = new System.IO.StreamReader("data.xml"); 
     overview = (List<patient>)reader.Deserialize(file);// throws exception here 
     file.Close(); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.InnerException.Message); 
    } 

而且我的模型类:

namespace WpfApplication1 
{ 

    [XmlRoot("patients"), XmlType("patient")] 
    public class patient 
    { 
     public patient() 
     { 
      this.Items = new ObservableCollection<patient>(); 
     } 
     [XmlElement(ElementName = "firstname")]  
     public string name { get; set; } 
     [XmlElement(ElementName = "lastname")] 
     public string surname { get; set; } 
     [XmlElement(ElementName = "age")] 
     public int age { get; set; } 
     [XmlElement(ElementName = "gender")] 
     public string gender { get; set; } 
     [XmlElement(ElementName = "exams")] 
     public List<exam> exams { get; set; } 

     [XmlElement(ElementName = "patients")] 
     public ObservableCollection<patient> Items { get; set; } 
    } 
    [XmlRoot("exams"), XmlType("exam")] 
    public class exam 
    { 
     [XmlElement(ElementName = "id")] 
     public int id { get; set; } 
     [XmlElement(ElementName = "date")] 
     public DateTime date { get; set; } 
     [XmlElement(ElementName = "comment")] 
     public string comment { get; set; } 
    } 
} 

我搜索很多在网络上的一切似乎很好,但我失去了一些东西..

回答

0

添加XmlRootAttributeXmlSerializer

var rootAttribute = new XmlRootAttribute(); 
rootAttribute.ElementName = "patients"; 
rootAttribute.IsNullable = true; 
XmlSerializer reader = 
     new XmlSerializer(typeof(List<patient>), rootAttribute); 

此外,此行不需要:

[XmlRoot("patients"), XmlType("patient")]