编辑特定的XDocument元素 [英] Edit specific Element in XDocument

查看:174
本文介绍了编辑特定的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?

比方说,我想改变一个特定的余额 秘技

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

我想访问由的ID号(这些编号是唯一的)

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

然后我想改变的平衡值(例如50个),然后保存这些更改我的文件。

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

推荐答案

通过使用System.Xml.Linq的; 变成

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

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

 doc.Save(fileName2);

这篇关于编辑特定的XDocument元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆