编辑 XDocument 中的特定元素 [英] Edit specific Element in XDocument
问题描述
我最近开始学习 C#,但在使用 XML.Linq
存储数据时遇到了问题.我希望这个问题是可以理解的,因为我还不熟悉所有正确的术语,而且英语不是我的第一语言.
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.
我想更新一个现有的 XDocument 文件,如下所示:
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?
假设我想更改特定存档的平衡.
我想通过 IdNumber(这些数字是唯一的)访问存档游戏
I want to access the savegame by IdNumber (these numbers are unique)
然后我想更改 balance 的值(例如更改为 50),然后将这些更改保存到我的文档中.
Then I want to change the value of balance (for example to 50) and then save these changes to my document.
推荐答案
随着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);
这篇关于编辑 XDocument 中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!