[英]How to update specific values in XML document with C#
我最近問了一個類似的問題,但是建議的解決方案有問題,因此這次與示例代碼略有不同。 我有一個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#的新手,因此,如果可能的話,使用盡可能多的上述代碼會使我的生活更輕松。 謝謝,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.