更新了以下建議的更改。C# - 一次讀取XML的問題。還有錯誤檢查是否存在。 [XElement]
我一直在嘗試解決這個問題大約2天,現在持續3-4小時,並且沒有太遠。任何幫助表示讚賞。
好的,所以基本上每次有人死亡時都會運行。如果我運行它一次,它工作正常。但是,如果我再次運行它,它什麼也不返回。
public static string Death(string username)
{
if (File.Exists(path))
{
XElement kd = XElement.Load(path);
Console.WriteLine("[SimplePlugin] Death Recorded for: " + username + "!");
var player = kd.Elements("player").Single(p => p.Attribute("name").Value == username);
int add = int.Parse(player.Element("deaths").Value) + 1; //Dies Here.
player.SetElementValue("deaths", add);
player.Save(path);
kills = int.Parse(player.Element("kills").Value);
deaths = int.Parse(player.Element("deaths").Value);
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
else
{
Console.WriteLine("[SimpleStats] Writing SimpleConfig.XML...");
XElement kd = new XElement(
"SimpleStats",
new XElement("player",
new XAttribute("name", username),
new XElement("kills", 0),
new XElement("deaths", 0),
new XElement("time", 0)));
kd.Save(path);
Console.WriteLine("[Simple] Done!");
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
}
我的第二個問題是當在XML玩家名稱= 「NAME」 已經存在。即使用戶名匹配,它也會重新創建它。
代碼此:
public static string Load(string username)
{
if (File.Exists(path))
{
XElement kd = XElement.Load(path);
var player = kd.Elements("player").SingleOrDefault(p => p.Attribute("name").Value == username);
Console.WriteLine(player);
if (player == null)
{
Console.WriteLine("[SimplePlugin] Writing new XML data for " + username + ".");
kd.Add(new XElement("player",
new XAttribute("name", username),
new XElement("kills", 0),
new XElement("deaths", 0),
new XElement("time", 0)));
kd.Save(path);
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
else
{
kills = int.Parse(player.Element("kills").Value);
deaths = int.Parse(player.Element("deaths").Value);
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
}
else
{
Console.WriteLine("Doesnt Exist");
Console.WriteLine("[SimpleStats] Writing SimpleConfig.XML...");
XElement player = new XElement(
"SimpleStats",
new XElement("player",
new XAttribute("name", username),
new XElement("kills", 0),
new XElement("deaths", 0),
new XElement("time", 0)));
player.Save(path);
Console.WriteLine("[Simple] Done!");
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
}
的字符串被髮送到負載()。加載檢查以查看xml是否存在。如果沒有,創建它。如果是這樣,創建它。然後檢查用戶名是否存在於xml數據中。如果它讀取並返回該字符串。如果沒有,它會創建它。
另外:「這個問題沒有顯示任何研究工作;它不清楚或沒有用」 如何?
你是什麼意思與「會死在那個地方」?我假設你得到一個例外:哪一個? – ChrisWue
錯誤信息在這裏很有幫助。爲什麼你不使用數據庫呢? –
呃,對不起沒有說明,'死'我的意思是不返回任何東西。數據庫? – Chris