我如何在C#中将XML文件读取到一个类中?

15 浏览
0 Comments

我如何在C#中将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月21日
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; }
}

反序列化函数:

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

你可以把xml保存到文件中,然后使用xsd生成C#类。具体操作如下:\n

    \n

  1. 将文件保存到磁盘(我把它命名为foo.xml)
  2. \n

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

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

\n这样就可以得到一个C#代码文件,它应该能够通过XmlSerializer读取数据:\n

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

\n(将生成的foo.cs包含在项目中)

0