我正在尝试通过执行以下操作将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; }
}发布于 2011-01-25 22:26:49
顺便说一下,您可能会发现使用XSD从您的类生成XML有一些好处。
发布于 2011-01-25 21:46:36
我打赌这是由于日期格式的原因。还缺少xmlns声明。
Felice的建议很好。在尝试反序列化之前,尝试使用序列化产生所需的结果
发布于 2011-01-25 21:45:28
Read this page in the MSDN来验证您的代码。页面中间的黄色注释指定了集合必须满足的要求。
另外:将Car类型也传递给序列化构造函数。
编辑报告和汽车标签没有关闭!
编辑
以下是序列化时的输出。发现不同之处有很多。最大的问题是如何序列化数组。开始使用复数(Cars,Owners)来表示集合,这将使集合更具可读性。
<?xml version="1.0" encoding="utf-8"?>
<CarCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Car>
<Car Make="make">
<CarOwner>
<CarOwner Name="name1">
<Report>
<Report Type="rtype">
<Report>
<Report>2011-01-25T15:22:52.703125+01:00</Report>
</Report>
</Report>
</Report>
</CarOwner>
</CarOwner>
</Car>
<Car Make="make2">
<CarOwner>
<CarOwner Name="name3">
<Report>
<Report Type="rtype">
<Report>
<Report>2011-01-25T15:22:52.703125+01:00</Report>
</Report>
</Report>
</Report>
</CarOwner>
</CarOwner>
</Car>
</Car>
https://stackoverflow.com/questions/4793921
复制相似问题