C# 编辑 XDocument 中的特定元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18508765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:25:59  来源:igfitidea点击:

Edit specific Element in XDocument

c#xmllinq

提问by Matthias Wei?

I recently started learning C# and I ran into a problem using XML.Linqto 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.

我最近开始学习 C#,但在使用XML.Linq存储数据时遇到了问题。我希望这个问题是可以理解的,因为我还不熟悉所有正确的术语,而且英语不是我的第一语言。

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:

我想更新一个现有的 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> 

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

更改特定元素中的值的最简单方法是什么?

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

假设我想更改特定savegame平衡

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

我想通过IdNumber访问保存游戏(这些数字是唯一的)

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

然后我想更改balance的值(例如更改为 50),然后将这些更改保存到我的文档中。

采纳答案by Henk Holterman

With using System.Xml.Linq;it becomes

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

回答by No Idea For Name

here's a simple way to do this:

这是一个简单的方法来做到这一点:

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

this code only change the balance of id "1"

此代码仅更改 id "1" 的余额

it does it by going through the children of "savegames" and checking for each item the "IdNumber"

它通过遍历“savegames”的子项并检查“IdNumber”的每个项目来实现

回答by gwiazdorrr

I think that the most compact way of doing it is using XDocument (System.Xml.Linq) and XPath extensions (System.Xml.XPath):

我认为最简洁的方法是使用 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);

Once you learn XPath you never really want to go back to enumerating nodes manually.

一旦您学习了 XPath,您就再也不想回到手动枚举节点了。

EDIT: what does the query mean:

编辑:查询是什么意思:

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

You can find XPath help here, and the updated link here.

你可以找到XPath的帮助下在这里,并在这里更新的链接

回答by Suraj Singh

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

   }