Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c# - Edit specific Element in XDocument

I recently started learning C# and I ran into a problem using XML.Linq to store data. I hope the question is understandable as I am not familiar with all the correct terms yet and as English isn't my first language.

I read a lot of Questions/googled but I can not figure it out myself.

I want to update an existing XDocument File that looks like this:

<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> 

What is the easiest way to change a value in a specific Element?

Let's say I want to change the balance of a specific savegame.

I want to access the savegame by IdNumber (these numbers are unique)

Then I want to change the value of balance (for example to 50) and then save these changes to my document.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With using System.Xml.Linq; it becomes

 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...