如何在不覆盖以前数据的情况下将数据序列化为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数据并将其存储到变量中?
答案 0 :(得分:4)
听起来你应该创建一个List<Actor>
- 然后你可以从一个条目的列表开始,序列化该列表,然后下一次反序列化列表,添加一个actor,然后再次序列化,这样你下面的时间就会在列表中有两个条目,等等。
答案 1 :(得分:1)
要读取数据,请将文件加载到StreamReader,然后在序列化程序上使用Deserialize方法:
XmlSerializer serializer = new XmlSerializer(typeof(Actor));
TextReader textReader = new StreamReader(@"c:\users\Desktop\actor.xml");
Actor actor = (Actor)serializer.Deserialize(textReader);
textReader.Close();
(假设您只有一个actor保存在XML文件中) 为了不覆盖,我建议你读取数据,如上所述,然后更新对象,最后写入XML文件。这样就可以根据需要保留XML文件中最初的内容。
(假设你想在XML文件中有很多actor) 您可能希望序列化List而不仅仅是Actor。如果是这样,您仍然可以读取数据(转换为List而不是),根据需要更新列表,然后序列化回XML文件。
PS:我建议您在C#中使用“using”语句,而不是在读者/作者和其他IDisposable对象上使用“Close”。
答案 2 :(得分:0)
只需将一个true传递给StreamWriter的构造函数
static public void SerializeToXML(Actor actor)
{
XmlSerializer serializer = new XmlSerializer(typeof(Actor));
TextWriter textWriter = new StreamWriter(@"c:\users\Desktop\actor.xml",true);
serializer.Serialize(textWriter, actor);
textWriter.Close();
}
就修复Xml而言,您可以使用Linq To XML http://blogs.msdn.com/b/wriju/archive/2008/02/18/linq-to-xml-creating-complex-xml-through-linq.aspx创建有效的XML并一次性将其保存到文件中