我正在尝试在 XML 文件中写入一些信息,结构应该是:
<Scoreboard>
<Match>
<name>Dummy</name>
<score>1234</score>
</Match>
<Match>
<name>Sample</name>
<score>4567</score>
</Match>
</Scoreboard>
问题是我只能写一个条目,如果我插入另一个“匹配”,旧的会被覆盖。
例如,如果我有:
<Scoreboard>
<Match>
<name>Dummy</name>
<score>1234</score>
</Match>
</Scoreboard>
然后我想添加另一个条目,旧条目将被删除,我只有新条目,例如:
<Scoreboard>
<Match>
<name>Sample</name>
<score>4567</score>
</Match>
</Scoreboard>
我会知道如何在不覆盖旧条目的情况下编写新条目。
这是我的代码:
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
//If file doesn't exist, then create it.
if (!isoStore.FileExists("scoreboard.xml"))
{
XDocument doc = new XDocument(new XElement("Scoreboard"));
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("scoreboard.xml", System.IO.FileMode.Create, isoStore))
{
doc.Save(isoStream);
}
}
else
{
//Else open it and write a new element which is a child of Scoreboard
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("scoreboard.xml", System.IO.FileMode.Open, isoStore))
{
XDocument doc1 = XDocument.Load(isoStream);
var newElement = new XElement("Match",
new XElement("name", VarGlobal.Name),
new XElement("score", VarGlobal.Score));
doc1.Element("Scoreboard").Add(newElement);
Messaggio.Text = doc1.ToString();
}
}
}