Edit specific Element in XDocument

前端 未结 4 1571
萌比男神i
萌比男神i 2020-11-29 07:23

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 co

相关标签:
4条回答
  • 2020-11-29 07:34
       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");
    
       }
    
    0 讨论(0)
  • 2020-11-29 07:35

    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);
    
    0 讨论(0)
  • 2020-11-29 07:40

    I think that the most compact way of doing it is using XDocument (System.Xml.Linq) and XPath extensions (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.

    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.

    0 讨论(0)
  • 2020-11-29 07:53

    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"

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

    0 讨论(0)
提交回复
热议问题