【发布时间】:2011-01-27 06:13:21
【问题描述】:
我正在尝试通过执行以下操作将 xml 文件反序列化为 .NET 对象:
CarCollection myCarCollection = null;
string path = "CarCollection.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
myCarCollection= (CarCollection)serializer.Deserialize(reader);
reader.Close();
这是我正在使用的 xml 文件:
<?xml version="1.0" encoding="utf-8" ?>
<CarCollection>
<Car ID="A">
<CarType Make="Ford" Model="Focus" />
<CarOwner Name="Tom">
<Report Type="Service">
<ReportList>
<Date>20-08-2010</Date>
</ReportList>
</Report>
</CarOwner>
</Car>
<Car ID="B">
<CarType Make="Vauxhall " Model="Corsa" />
<CarOwner Name="Joe">
<Report Type="Service">
<ReportList>
<Date>10-10-2008</Date>
<Date>10-10-2009</Date>
<Date>10-10-2010</Date>
</ReportList>
</Report>
<Report Type="Accident">
<ReportList>
<Date>20-01-2011</Date>
</ReportList>
</Report>
</CarOwner>
</Car>
</CarCollection>
我尝试了很多东西,但似乎无法正常工作。
谁能帮助我如何反序列化为 .NET 对象。
这里是 C# 对象
[Serializable()]
[XmlRoot("CarCollection")]
public class CarCollection
{
[XmlArray("Car")]
[XmlArrayItem("Car", typeof(Car))]
public Car[] Cars { get; set; }
}
[Serializable()]
public class Car
{
[XmlAttribute("Make")]
public string CarMakeType { get; set; }
[XmlAttribute("Model")]
public string CarModelType { get; set; }
[XmlArray("CarOwner")]
[XmlArrayItem("CarOwner", typeof(CarOwner))]
public CarOwner[] CarOwners { get; set; }
}
[Serializable()]
public class CarOwner
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlArray("Report")]
[XmlArrayItem("Report", typeof(Report))]
public Report[] Reports { get; set; }
}
[Serializable()]
public class Report
{
[XmlAttribute("Type")]
public string Type { get; set; }
[XmlArray("Report")]
[XmlArrayItem("Report", typeof(DateTime))]
public DateTime[] Reports { get; set; }
}
【问题讨论】:
-
请张贴为什么它不工作,错误和什么不工作。还将代码发布到 CarCollection 类
-
请告诉我们您对 Car 对象的定义。另外,它做错了什么。是否抛出任何异常?
-
您是如何创建 CarCollection 类的?它是从 XML 模式派生的吗?手工编码?还有什么?
-
您需要粘贴
Car和CarCollection的代码 -
另一个测试是创建一个 CarCollection 并对其进行序列化,检查它是否与您尝试反序列化的 xml 兼容
标签: c# .net xml serialization