如何反序列化XML文档

30 浏览
0 Comments

如何反序列化XML文档

我如何反序列化这个XML文档:



  
    1020
    Nissan
    Sentra
  
  
    1010
    Toyota
    Corolla
  
  
    1111
    Honda
    Accord
  

我有这个:

[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;
    }
}

似乎不起作用 🙁

admin 更改状态以发布 2023年5月24日
0
0 Comments

这是一个可用的版本。我将 XmlElementAttribute 标签更改为 XmlElement,因为在 xml 文件中,StockNumber、Make 和 Model 值是元素,而不是属性。同时,我删除了 reader.ReadToEnd(); (该 函数 读取整个流并返回一个字符串,因此 Deserialize() 函数不能再使用该读取器,......位置已经在流的末尾了)。我也稍微改了一下命名:)。

下面是类:

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }
    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }
    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}
[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

Deserialize 函数:

CarCollection cars = null;
string path = "cars.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

稍作修改的 xml 文件(我需要添加一个新元素来包含 ……. Net 对于反序列化数组有点挑剔):




  
    1020
    Nissan
    Sentra
  
  
    1010
    Toyota
    Corolla
  
  
    1111
    Honda
    Accord
  


0
0 Comments

\n\n你能够把xml保存到一个文件中,然后使用xsd生成C#类,这样怎么样?\n\n

    \n

  1. 将文件写到磁盘上(我给它命名为foo.xml)
  2. \n

  3. 生成xsd:xsd foo.xml
  4. \n

  5. 生成C#:xsd foo.xsd /classes
  6. \n

\n\n然后,生成了一个C#代码文件,可以通过XmlSerializer读取数据。\n\n

    XmlSerializer ser = new XmlSerializer(typeof(Cars));
    Cars cars;
    using (XmlReader reader = XmlReader.Create(path))
    {
        cars = (Cars) ser.Deserialize(reader);
    }

\n\n(在项目中需要包含生成的foo.cs文件)

0