XML 序列化程序类型错误
本文关键字:错误 类型 程序 序列化 XML | 更新日期: 2023-09-27 18:36:34
我想序列化一个包含以下内容的 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; }
}
}
我在网上搜索了很多,一切似乎都很好,但我错过了一些东西。
将XmlRootAttribute
添加到您的XmlSerializer
:
var rootAttribute = new XmlRootAttribute();
rootAttribute.ElementName = "patients";
rootAttribute.IsNullable = true;
XmlSerializer reader =
new XmlSerializer(typeof(List<patient>), rootAttribute);
此外,不需要此行:
[XmlRoot("patients"), XmlType("patient")]