XML停止覆盖/保存多个条目
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML停止覆盖/保存多个条目相关的知识,希望对你有一定的参考价值。
当前我正在使用此代码创建XML文件
{
XmlSerializer sr = new XmlSerializer(obj.GetType());
TextWriter writer = new StreamWriter(filename);
sr.Serialize(writer, obj);
writer.Close();
}
问题是,它总是会覆盖我之前所做的输入。我如何进行多个输入并保存(在Combobox / DropDownList中的字符?)。
这里是我的其余代码(btnSave btnLoad)
{
try
{
Daten daten = new Daten();
daten.GAME = txtGame.Text;
daten.PLATFORM = txtPlatform.Text;
daten.RELEASED = txtReleased.Text;
SaveData.SaveDaten(daten, "gameregister.xml");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
if (File.Exists("gameregister.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(Daten));
FileStream read = new FileStream("gameregister.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Daten daten = (Daten)xs.Deserialize(read);
txtGame.Text = daten.GAME;
txtPlatform.Text = daten.PLATFORM;
txtReleased.Text = daten.RELEASED;
read.Close();
}
}
ps:我必须将XML用于此特定任务。
答案
关于您的问题,您想将多个实例序列化为XML。
您可以尝试以下代码来获取它。
Private void BtnSave_Click(object sender,EventArgs e)
{
Daten daten=new Daten();
daten.GAME=txtGame.Text;
daten.PLATFORM=txtPlatform.Text;
datem.RELEASED=txtReleased.Text;
List<Daten> lisrt=new List<Daten>();
String path=”d:\\gameregister.xml”;
if(File.Exists(path))
{
StreamReader read=new StreamReader(path);
XmlSerializer xc=new XmlSerializer(typeof(List<Daten>));
list=(List<Daten>)xc.Deserialize(read);
read.Close();
Textwriter writer=new StreamWriter(path);
list.Add(daten);
xc.Serialize(writer,list);
writer.Close();
MessageBox.Show(“Serialization succeeded again!;”);
}
else
{
list.Add(daten);
XmlSerializer xs=new XmlSerializer(typeof(List<Daten>));
Textwriter writer=new StreamWriter(path);
xs.Serialize(writer,list);
writer.Close();
MessageBox.Show(“Serialization successful!”);
}
}
以上是关于XML停止覆盖/保存多个条目的主要内容,如果未能解决你的问题,请参考以下文章