现在我想要将汽车和人员保存在XML文件中。但我之前从未使用过XML,我是初学者。
所以我想从汽车开始。我有一个汽车清单和生产商,颜色,车牌,..."
所以这就是我所拥有的:
public static void SaveFileAuto(List<Car> cars)
{
Car car = new Car();
XmlSerializer ser = new XmlSerializer(typeof(Car));
StringWriter writer = new StringWriter();
FileStream str = new FileStream(@"car.xml", FileMode.Create);
ser.Serialize(str, cars);
}
所以,我不知道,接下来该做什么或者缺少什么或错误。
答案 0 :(得分:4)
首先,Car car = new Car();
行以及StringWriter writer...
行显然已过时。
其次,您要序列化List<Car>
,而不仅仅是Car
。因此,您必须相应地创建XmlSerializer
。
第三点:在using
语句中包含流的使用,因此在使用后它会被彻底关闭:
public static void SaveFileAuto(List<Car> cars)
{
// create serializer for typeof(List<Car>) not typeof(Car)
XmlSerializer ser = new XmlSerializer(typeof(List<Car>));
using (FileStream str = new FileStream(@"car.xml", FileMode.Create))
ser.Serialize(str, cars);
}
要再次加载和反序列化xml文件,您还可以使用XmlSerializer
:
XmlSerializer serializer = new XmlSerializer(typeof(List<Car>));
List<car> cars;
using(FileStream stream = new FileStream(@"car.xml", FileMode.Open))
cars = (List<Car>)serializer.Deserialize(stream);
答案 1 :(得分:1)
您可以根据自己的喜好创建xml。你最好使用XmlSerializer。 Referenced From Here
// Your Car Class
public class Car
{
public string Producer{ get; set; }
public string Colour{ get; set; }
public int LicensePlate { get; set; }
public int CarID { get; set; }
}
// The List<Car>
var cars= new List<Car>(){
new Car() { Producer= "Ford", Colour= "Red", LicensePlate= 123},
new Car() { Producer= "Chevy", Colour= "Green", LicensePlate= 333}
};
// Build the document
public static void SaveFileAuto(List<Car> cars)
{
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
// This is the root of the document
new XElement("Cars",
from car in cars
select
new XElement("Car", new XAttribute("ID", car.CarID),
new XElement("Producer",car.Producer),
new XElement("Colour", car.Colour),
new XElement("LicensePlate", car.LicensePlate));
// Write the document to the file system
xdoc.Save("C:/Working Directory/Cars.xml");
}