[英]How to deserialize xml objects back to a class list
我正在嘗試創建一個 windows 表單應用程序,其中我在業務 class 列表中創建車輛 class 對象的列表。 當一個新項目被添加到列表中時,該文件被序列化。 I have created a class called Vehicle that contains the xml attributes, a method for adding a new instance of the vehicle class, and a way to serialize the data to an xml file. 我想關閉應用程序並重新打開它以在數據網格視圖等視圖中顯示這些數據。 我目前遇到的問題是我不確定如何將數據反序列化回 class 列表並顯示它。 當我退出應用程序並再次打開它然后嘗試添加新車輛時,它會覆蓋 xml 文件中的當前數據。
這是我的業務 class 和我的序列化方法:
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace VehicleSystem
{
public class Business
{
private static List<Vehicle> _vehicleList = new List<Vehicle>();
public static List<Vehicle> VehicleList
{
get => _vehicleList;
}
public static void Save()
{
XmlSerializer serial = new XmlSerializer(typeof(List<Vehicle>));
using (FileStream file = new FileStream("C:\\temp\\data.xml", FileMode.Create))
{
serial.Serialize(file, VehicleList);
file.Close();
}
}
}
}
這是車輛 class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace VehicleSystem
{
[XmlType("vehicle")]
[Serializable]
public class Vehicle
{
private int _cost;
private int _year;
private string _make;
private string _model;
private string _registration;
[XmlElement("Registration")]
public string Registration { get => _registration; set => _registration = value; }
[XmlElement("Model")]
public string Model { get => _model; set => _model = value; }
[XmlElement("Make")]
public string Make { get => _make; set => _make = value; }
[XmlElement("Year")]
public int Year { get => _year; set => _year = value; }
[XmlElement("Cost")]
public int Cost { get => _cost; set => _cost = value; }
public Vehicle(string registration, string model, string make, int year, int cost)
{
Registration = registration;
Model = model;
Make = make;
Year = year;
Cost = cost;
}
}
}
這是車輛的創建:
Business.VehicleList.Add(new Vehicle("ABC123","Hilux","Toyota", 1992, 123));
Business.Save();
這就是 xml 數據的樣子
<?xml version="1.0"?>
-<ArrayOfVehicle xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<vehicle>
<Registration>ABC123</Registration>
<Model>Hilux</Model>
<Make>Toyota</Make>
<Year>1992</Year>
<Cost>123</Cost>
</vehicle>
</ArrayOfVehicle>
我如何將這些數據反序列化回我的VehicleList
並將其顯示到 datagridview 中?
您只需要放入數據集,然后將零表設為 DGV 的數據源。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication189
{
class Program
{
const string FILENAME = @"C:\temp\test.xml";
static void Main(string[] args)
{
DataSet ds = new DataSet();
ds.ReadXml(FILENAME);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.