我最近问了一个类似的问题,但提出的解决方案有问题,所以这次我用示例代码稍微改一下。我有一个存储游戏玩家数据的 XML 文件。我只需要定期从这个 XML 文件中找到一个玩家,并在特定玩家玩游戏时更新他的相关数据:
<?xml version="1.0"?>
<PlayerStats xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Player>
<Name>Jack</Name>
<WinCount>3</WinCount>
<PlayCount>9</PlayCount>
<Balance>500</Balance>
</Player>
<Player>
<Name>John</Name>
<WinCount>3</WinCount>
<PlayCount>9</PlayCount>
<Balance>940</Balance>
</Player>
</PlayerStats>
我需要代码来识别特定玩家(例如 John)并根据 C# 变量更新 Wincount、Playcount 和 Balance 数字。这是我正在使用的一些示例 C# 代码:
XmlDocument doc = new XmlDocument();
doc.Load(xmlfilepath);
XmlNode player;
XmlNode root = doc.DocumentElement;
// below correctly pulls data for the specific player
player = root.SelectSingleNode("descendant::Player[Name='"+Form1.strPlayerName+"']");
// the "inner xml" for player = "<Name>John</Name><WinCount>3</WinCount><PlayCount>9</PlayCount><Balance>940</Balance>"
// since "Balance" was last, I tried using "LastChild" and the code below worked
player.LastChild.InnerText = Form1.decBalance.ToString(); //updates balance succesfully
doc.Save(xmlfilepath);
所以这适用于“LastChild”,但我如何更改“Wincount”、“PlayCount”和“Balance”而不将它们作为第一个或最后一个引用?在使用 LINQ 和 XML 序列化等之前,我得到了一些建议,但它们引起了问题,我还不了解 LINQ。我真的很想使用 XmlDocument bc 我觉得这段代码已经完成了 95% 的工作,但我缺少一些简单的东西。我是 C# 新手,所以尽可能多地使用上面的代码会让我的生活更轻松。谢谢,