我试图写在一个XML文件中的一些信息,结构应该是:如何在C#中使用LINQ在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();
}
}
}
如果该文件存在,您正在加载它并追加一个新值 - 但之后您不再保存它。所以我没有看到文件内容将如何被替换...... –
但是,如果我不保存它,那么当我再次加载它时为什么会看到新的值?我应该如何保存它? –
如果你不保存它,你*不会*看到新的值。你不会。我怀疑问题出在'isoStore.FileExists'中。你应该能够通过调试来看到。 –