我正在尝试将多个条目保存到现有的 xml 文档中。但我没有得到想要的结果。
我有以下代码:
public static void recordScore(ScoreModel scoreModel)
{
var path = "../../Media/Leaderboard/Leaderboard.xml";
var saveModel = new LeaderboardModel();
Stream fs = new FileStream(path, FileMode.Open);
XmlReader reader = new XmlTextReader(fs);
XmlSerializer serializer = new XmlSerializer(typeof(LeaderboardModel));
if (serializer.CanDeserialize(reader))
{
LeaderboardModel o = (LeaderboardModel) serializer.Deserialize(reader);
saveModel.ScoreModels.AddRange(o.ScoreModels);
}
fs.Close();
saveModel.ScoreModels.Add(scoreModel);
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(LeaderboardModel));
System.IO.FileStream file = System.IO.File.Open(path, System.IO.FileMode.Append);
writer.Serialize(file, saveModel);
file.Close();
}
我在xml文件中的输出如下:
<?xml version="1.0"?>
<LeaderboardModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ScoreModels>
<ScoreModel>
<Name>Test</Name>
<GameSpeed>Normal</GameSpeed>
<Score>11</Score>
</ScoreModel>
</ScoreModels>
</LeaderboardModel><?xml version="1.0"?>
<LeaderboardModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ScoreModels>
<ScoreModel>
<Name>Test</Name>
<GameSpeed>Normal</GameSpeed>
<Score>11</Score>
</ScoreModel>
</ScoreModels>
如您所见,它每次都输出 LeaderboardModel 和 ScoreModels。它应该只写一次,然后在该根下添加新的 ScoreModel。
相关分类