如何反序列化XML文档

如何反序列化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;
    }}

似乎不起作用:-(


慕标琳琳
浏览 633回答 4
4回答

梵蒂冈之花

你如何将xml保存到文件中,并使用xsd生成C#类?将文件写入磁盘(我将其命名为foo.xml)生成xsd:&nbsp;xsd foo.xml生成C#:&nbsp;xsd foo.xsd /classesEt voila - 和C#代码文件应该能够通过XmlSerializer以下方式读取数据:&nbsp;&nbsp;&nbsp;&nbsp;XmlSerializer&nbsp;ser&nbsp;=&nbsp;new&nbsp;XmlSerializer(typeof(Cars)); &nbsp;&nbsp;&nbsp;&nbsp;Cars&nbsp;cars; &nbsp;&nbsp;&nbsp;&nbsp;using&nbsp;(XmlReader&nbsp;reader&nbsp;=&nbsp;XmlReader.Create(path)) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cars&nbsp;=&nbsp;(Cars)&nbsp;ser.Deserialize(reader); &nbsp;&nbsp;&nbsp;&nbsp;}(包括项目中生成的foo.cs)
打开App,查看更多内容
随时随地看视频慕课网APP