locked
How to update xml file node values using XDocument RRS feed

  • Question

  • please share a small sample code which guide me how to use XDocument to update xml file. thanks
    Thursday, April 16, 2020 4:43 PM

Answers

  • Here is a small sample:

    var xml = @"
    <sample>
      <name>John</name>
      <parents>
        <name>Eric</name>
        <name>Jane</name>
      </parents>
    </sample>";
    
    File.WriteAllText("input.xml", xml);
    
    var document = XDocument.Load("input.xml");
    
    document.Element("sample")
            .Element("name").Value = "New John";
    
    document.Element("sample")
            .Element("parents")
            .Elements("name")
            .ElementAt(1).Value = "New Jane";
    
    document.Save("updated-output.xml");

    I hope this helps.

    • Marked as answer by Sudip_inn Friday, April 17, 2020 6:50 AM
    Thursday, April 16, 2020 5:15 PM
  • Hi Sudip,

    This C# Console application helps you to change from an xml file per student ID and save in the same name xml file.

    student xml file,

    <?xml version="1.0" encoding="utf-8" ?>
    <Root>
      <record>
        <id>1</id>
        <first_name>Nollie</first_name>
        <last_name>Cassella</last_name>
        <email>ncassella0@symantec.com</email>
      </record>
      <record>
        <id>2</id>
        <first_name>Cad</first_name>
        <last_name>Cossor</last_name>
        <email>ccossor1@mayoclinic.com</email>
      </record>
      <record>
        <id>3</id>
        <first_name>Verna</first_name>
        <last_name>Easum</last_name>
        <email>veasum2@prnewswire.com</email>
      </record>
      <record>
        <id>4</id>
        <first_name>Claus</first_name>
        <last_name>Pringley</last_name>
        <email>cpringley3@meetup.com</email>
      </record>
      <record>
        <id>5</id>
        <first_name>Guthry</first_name>
        <last_name>Dyer</last_name>
        <email>gdyer4@mac.com</email>
      </record>
    </Root>

    C# Console application,

     class Program
        {
            static void Main(string[] args)
            {
    
                 
    
                XDocument xdoc = XDocument.Load("Students.xml");
    
                //Display xml content before modify
                foreach (XElement Outeritem in xdoc.Descendants("record"))
                {
                    foreach (XElement innerItem in Outeritem.Descendants())
                    {
                        Console.WriteLine(innerItem);
                    }
                }
    
    
    
                Console.WriteLine("###################################");
    
    
                Console.WriteLine("Please enter student Id to modify");
    
    
    
                var studentId = Console.ReadLine();
    
    
                
    
                IEnumerable<XElement> AllData = from st in xdoc.Root.Elements("record") where (string)st.Element("id") == studentId select st;
    
    
               
    
                //Display xml content before modify
                foreach (XElement Singleitem in AllData)
                {
                    foreach (XElement innerItem in Singleitem.Descendants())
                    {
                        Console.WriteLine(innerItem);
                    }
                }
    
                Console.WriteLine();
                Console.WriteLine("###################################");
    
    
    
                Console.WriteLine("Please enter new Frist name");
    
                var studentFName = Console.ReadLine();
    
    
                Console.WriteLine("Please enter new Last name");
    
                var studentLName = Console.ReadLine();
    
    
                Console.WriteLine("Please enter new Student email address");
    
                var studentEmail = Console.ReadLine();
    
    
    
                Console.WriteLine();
                Console.WriteLine("###################################");
    
                 
    
                if (AllData !=null)
                {
                    foreach (XElement item in AllData)
                    {
                        item.Element("first_name").SetValue(studentFName);
                        item.Element("last_name").SetValue(studentLName);
                        item.Element("email").SetValue(studentEmail);
                         
                    }
                }
    
    
               
    
    
                Console.WriteLine("The Student information has been updated.");
    
                Console.WriteLine();
                Console.WriteLine("###################################");
    
    
                //Display xml content after modify
                foreach (XElement Outeritem in xdoc.Descendants("record"))
                {
                    foreach (XElement innerItem in Outeritem.Descendants())
                    {
                        Console.WriteLine(innerItem);
                    }
                }
    
                //Save all changes
                xdoc.Save("Students.xml");
    
    
                Console.ReadKey();
            }
        }

    The result,
    The student data information before update


    Select student where Id =2

    Save changes and display
     


    Please remember to mark the replies as answers if they helped you :) ~

    • Marked as answer by Sudip_inn Friday, April 17, 2020 6:49 AM
    Thursday, April 16, 2020 5:55 PM

  • Hi Sudip_inn,
    You can use XDocument (System.Xml.Linq) to load the xml file, and use XPath extensions (System.Xml.XPath) to navigate to a specific node.
    XPath uses path expressions to select nodes or node-sets in an XML document.
    Here is a code example you can refer to.
    In the code example, I use XPathSelectElement method to navigate to the "balance" element which IdNumber value is "1".
    The xml file:

    <?xml version="1.0" encoding="utf-8"?>
    <Data>
      <IDCounter>2</IDCounter>
      <Highscores>
         .......
      </Highscores>
      <savegames>
        <savegame>
          <IdNumber>1</IdNumber>
          <salutation>Mr</salutation>
          <prename>Prename1</prename>
          <surname>Surname1</surname>
          <maximumbalance>100</maximumbalance>
          <balance>50</balance>
        </savegame>
        <savegame>
          <IdNumber>2</IdNumber>
          <salutation>Mr</salutation>
          <prename>Prename2</prename>
          <surname>Surname2</surname>
          <maximumbalance>100</maximumbalance>
          <balance>50</balance>
        </savegame>
      </savegames>
    </Data>
    static void Main(string[] args)
    {
        var xdoc = XDocument.Load(@"C:\User\Desktop\test.xml");
        xdoc.XPathSelectElement("//savegame/IdNumber[text()='1']/../balance").Value = "122";
        xdoc.Save(@"C:\Users\Desktop\test.xml");
    }

    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, April 17, 2020 2:26 AM

All replies

  • Here is a small sample:

    var xml = @"
    <sample>
      <name>John</name>
      <parents>
        <name>Eric</name>
        <name>Jane</name>
      </parents>
    </sample>";
    
    File.WriteAllText("input.xml", xml);
    
    var document = XDocument.Load("input.xml");
    
    document.Element("sample")
            .Element("name").Value = "New John";
    
    document.Element("sample")
            .Element("parents")
            .Elements("name")
            .ElementAt(1).Value = "New Jane";
    
    document.Save("updated-output.xml");

    I hope this helps.

    • Marked as answer by Sudip_inn Friday, April 17, 2020 6:50 AM
    Thursday, April 16, 2020 5:15 PM
  • Hi Sudip,

    This C# Console application helps you to change from an xml file per student ID and save in the same name xml file.

    student xml file,

    <?xml version="1.0" encoding="utf-8" ?>
    <Root>
      <record>
        <id>1</id>
        <first_name>Nollie</first_name>
        <last_name>Cassella</last_name>
        <email>ncassella0@symantec.com</email>
      </record>
      <record>
        <id>2</id>
        <first_name>Cad</first_name>
        <last_name>Cossor</last_name>
        <email>ccossor1@mayoclinic.com</email>
      </record>
      <record>
        <id>3</id>
        <first_name>Verna</first_name>
        <last_name>Easum</last_name>
        <email>veasum2@prnewswire.com</email>
      </record>
      <record>
        <id>4</id>
        <first_name>Claus</first_name>
        <last_name>Pringley</last_name>
        <email>cpringley3@meetup.com</email>
      </record>
      <record>
        <id>5</id>
        <first_name>Guthry</first_name>
        <last_name>Dyer</last_name>
        <email>gdyer4@mac.com</email>
      </record>
    </Root>

    C# Console application,

     class Program
        {
            static void Main(string[] args)
            {
    
                 
    
                XDocument xdoc = XDocument.Load("Students.xml");
    
                //Display xml content before modify
                foreach (XElement Outeritem in xdoc.Descendants("record"))
                {
                    foreach (XElement innerItem in Outeritem.Descendants())
                    {
                        Console.WriteLine(innerItem);
                    }
                }
    
    
    
                Console.WriteLine("###################################");
    
    
                Console.WriteLine("Please enter student Id to modify");
    
    
    
                var studentId = Console.ReadLine();
    
    
                
    
                IEnumerable<XElement> AllData = from st in xdoc.Root.Elements("record") where (string)st.Element("id") == studentId select st;
    
    
               
    
                //Display xml content before modify
                foreach (XElement Singleitem in AllData)
                {
                    foreach (XElement innerItem in Singleitem.Descendants())
                    {
                        Console.WriteLine(innerItem);
                    }
                }
    
                Console.WriteLine();
                Console.WriteLine("###################################");
    
    
    
                Console.WriteLine("Please enter new Frist name");
    
                var studentFName = Console.ReadLine();
    
    
                Console.WriteLine("Please enter new Last name");
    
                var studentLName = Console.ReadLine();
    
    
                Console.WriteLine("Please enter new Student email address");
    
                var studentEmail = Console.ReadLine();
    
    
    
                Console.WriteLine();
                Console.WriteLine("###################################");
    
                 
    
                if (AllData !=null)
                {
                    foreach (XElement item in AllData)
                    {
                        item.Element("first_name").SetValue(studentFName);
                        item.Element("last_name").SetValue(studentLName);
                        item.Element("email").SetValue(studentEmail);
                         
                    }
                }
    
    
               
    
    
                Console.WriteLine("The Student information has been updated.");
    
                Console.WriteLine();
                Console.WriteLine("###################################");
    
    
                //Display xml content after modify
                foreach (XElement Outeritem in xdoc.Descendants("record"))
                {
                    foreach (XElement innerItem in Outeritem.Descendants())
                    {
                        Console.WriteLine(innerItem);
                    }
                }
    
                //Save all changes
                xdoc.Save("Students.xml");
    
    
                Console.ReadKey();
            }
        }

    The result,
    The student data information before update


    Select student where Id =2

    Save changes and display
     


    Please remember to mark the replies as answers if they helped you :) ~

    • Marked as answer by Sudip_inn Friday, April 17, 2020 6:49 AM
    Thursday, April 16, 2020 5:55 PM

  • Hi Sudip_inn,
    You can use XDocument (System.Xml.Linq) to load the xml file, and use XPath extensions (System.Xml.XPath) to navigate to a specific node.
    XPath uses path expressions to select nodes or node-sets in an XML document.
    Here is a code example you can refer to.
    In the code example, I use XPathSelectElement method to navigate to the "balance" element which IdNumber value is "1".
    The xml file:

    <?xml version="1.0" encoding="utf-8"?>
    <Data>
      <IDCounter>2</IDCounter>
      <Highscores>
         .......
      </Highscores>
      <savegames>
        <savegame>
          <IdNumber>1</IdNumber>
          <salutation>Mr</salutation>
          <prename>Prename1</prename>
          <surname>Surname1</surname>
          <maximumbalance>100</maximumbalance>
          <balance>50</balance>
        </savegame>
        <savegame>
          <IdNumber>2</IdNumber>
          <salutation>Mr</salutation>
          <prename>Prename2</prename>
          <surname>Surname2</surname>
          <maximumbalance>100</maximumbalance>
          <balance>50</balance>
        </savegame>
      </savegames>
    </Data>
    static void Main(string[] args)
    {
        var xdoc = XDocument.Load(@"C:\User\Desktop\test.xml");
        xdoc.XPathSelectElement("//savegame/IdNumber[text()='1']/../balance").Value = "122";
        xdoc.Save(@"C:\Users\Desktop\test.xml");
    }

    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, April 17, 2020 2:26 AM
  • i would prefer this approach

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

    thanks

    Friday, April 17, 2020 6:51 AM