2013-08-29 35 views
27

我最近開始學習C#,並遇到一個問題,使用XML.Linq來存儲數據。我希望這個問題是可以理解的,因爲我還不熟悉所有正確的術語,因爲英語不是我的第一語言。編輯XDocument中的特定元素

我讀了很多問題/谷歌搜索,但我無法弄清楚自己。

我想更新,看起來像這樣一個現有的XDocument文件:

<Data> 
    <IDCounter>2</IDCounter> 
    <Highscores> 
    ....... 
    </Highscores> 
    <savegames> 
    <savegame> 
     <IdNumber>1</IdNumber> 
     <salutation>Mr</salutation> 
     <prename>Prename1</prename> 
     <surname>Surname1</surname> 
     <maximumbalance>100</maximumbalance> 
     <balance>100</balance> 
    </savegame> 
    <savegame> 
     <IdNumber>2</IdNumber> 
     <salutation>Mr</salutation> 
     <prename>Prename2</prename> 
     <surname>Surname2</surname> 
     <maximumbalance>100</maximumbalance> 
     <balance>100</balance> 
    </savegame> 
    </savegames> 
</Data> 

是什麼改變了某個元素的值,最簡單的方法?

比方說,我想換一個特定祕技餘額

我想的ID號訪問祕技(這些編號是唯一的)

然後我想改變的餘額值(例如50),然後保存這些更改我的文件。

回答

34

隨着using System.Xml.Linq;成爲

var doc = XElement.Load(fileName); 
var saveGame = doc 
     .Element("savegames") 
     .Elements("savegame") 
     .Where(e => e.Element("IdNumber").Value == "2") 
     .Single(); 

saveGame.Element("balance").Value = "50"; 

doc.Save(fileName); 
+0

出於某種原因,我有一個錯誤「對象引用未設置爲實例...」,然後我用'XDocument.Load(fileName)修復它;' – newbieguy

6

這裏有一個簡單的方法來做到這一點:

 XmlDocument doc = new XmlDocument(); 
    doc.Load(@"d:\tmp.xml"); 
    XmlNode node = doc["Data"]["savegames"]; 

    foreach (XmlNode childNode in node.ChildNodes) 
    { 
     if (childNode["IdNumber"].InnerText.Equals("1")) 
     { 
      childNode["balance"].InnerText = "88"; 
     } 

    } 
    doc.Save(@"d:\tmp.xml"); 

這個代碼僅更改ID爲「1」的平衡

它通過的「遊戲存檔」孩子們會和檢查每個做它項目 「的ID號」

+6

XmlDocument不是'簡單'的方法。這是古老的方式。 –

+1

@HenkHolterman(和upvoter)你是非常迂腐。它不是說「*簡單的方法」,而是簡單的方法。它仍然很簡單。 –

17

我認爲做的最簡潔的方法是使用的XDocument(System.Xml.Linq)和XPath擴展(System.Xml.XPath):

var xdoc = XDocument.Load(file); 
xdoc.XPathSelectElement("//savegame/IdNumber[text()='2']/../balance").Value = "50"; 
xdoc.Save(file); 

一旦你學會的XPath你從來沒有真正想回去手動列舉節點。

編輯:什麼是查詢平均:

//savegame/IdNumber[text()='2']/../balance" 
    |  |     |^balance element ... 
    |  |     ^... of parent ... 
    |  ^... of IdNumber element with inner value '2' ... 
^... of any savegame element in the doc 

你可以找到的XPath幫助here,和the updated link here

+2

這裏是更新的[鏈接](http:// www。 w3schools.com/xsl/xpath_intro.asp)到XPath幫助。 – Cooter

4
UpdateGameAttr(id , bal); 

    private void UpdateGameAttr(int id, int bal) 
    { 
     XDocument gmaes = XDocument.Load(@"D:\xxx\xxx\Game.xml");    

     XElement upd = (from games in games.Descendants("savegame") 
         where games.Element("IdNumber").Value == id.ToString() 
         select games).Single(); 
     upd.Element("balance").Value = bal.ToString(); 
     gmaes.Save(@"D:\xxxx\xxx\Game.xml"); 

    }