如何在不覆盖以前数据的情况下将数据序列化为 xml?在这段代码中,我可以制作 XML 文件,但是当我再次运行它时,我会覆盖我之前保存的内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
namespace ActorGenerator
{
class Program
{
static void Main()
{
Console.Write("How many actors you want to add? ");
int max = 0;
max = int.Parse(Console.ReadLine());
for (int i = 0; i < max; i++)
{
int x = i + 1;
Console.WriteLine("////////////////////////ACTOR" + x + "/////////////////////////////////");
Actor actor1 = new Actor();
Console.Write("NAME (string): "); actor1.Name = Console.ReadLine();
Console.Write("AGE (int): "); actor1.Age = int.Parse(Console.ReadLine());
Console.Write("FOCUS (string): "); actor1.Focus = Console.ReadLine();
Console.Write("PRICE (int): "); actor1.Price = int.Parse(Console.ReadLine());
Console.Write("CONTRACTED (true/false): "); actor1.Contracted = bool.Parse(Console.ReadLine());
Console.Write("PLAYING IN FILM (true/false): "); actor1.PlayingInFilm = bool.Parse(Console.ReadLine());
Console.Write("SKILL (int): "); actor1.Skill = int.Parse(Console.ReadLine());
SerializeToXML(actor1);
}
}
static public void SerializeToXML(Actor actor)
{
XmlSerializer serializer = new XmlSerializer(typeof(Actor));
TextWriter textWriter = new StreamWriter(@"c:\users\Desktop\actor.xml");
serializer.Serialize(textWriter, actor);
textWriter.Close();
}
}
public class Actor
{
public string Name { get; set; }
public int Age { get; set; }
public string Focus { get; set; }
public int Price { get; set; }
public bool Contracted { get; set; }
public bool PlayingInFilm { get; set; }
public int Skill { get; set; }
}
}
另外,如何读取 XML 数据并将其存储到变量中?