如何反序列化XML文档如何反序列化此XML文档:<?xml version="1.0" encoding="utf-8"?><Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</Car>
<Car>
<StockNumber>1111</StockNumber>
<Make>Honda</Make>
<Model>Accord</Model>
</Car></Cars>我有这个:[Serializable()]public class Car{
[System.Xml.Serialization.XmlElementAttribute("StockNumber")]
public string StockNumber{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("Make")]
public string Make{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("Model")]
public string Model{ get; set; }}。[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]public class Cars{
[XmlArrayItem(typeof(Car))]
public Car[] Car { get; set; }}。public class CarSerializer{
public Cars Deserialize()
{
Cars[] cars = null;
string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/") + "cars.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Cars[]));
StreamReader reader = new StreamReader(path);
reader.ReadToEnd();
cars = (Cars[])serializer.Deserialize(reader);
reader.Close();
return cars;
}}似乎不起作用:-(
4 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
你如何将xml保存到文件中,并使用xsd生成C#类?
将文件写入磁盘(我将其命名为foo.xml)
生成xsd:
xsd foo.xml
生成C#:
xsd foo.xsd /classes
Et voila - 和C#代码文件应该能够通过XmlSerializer
以下方式读取数据:
XmlSerializer ser = new XmlSerializer(typeof(Cars)); Cars cars; using (XmlReader reader = XmlReader.Create(path)) { cars = (Cars) ser.Deserialize(reader); }
(包括项目中生成的foo.cs)
- 4 回答
- 0 关注
- 655 浏览
添加回答
举报
0/150
提交
取消