Appending to an XML file dynamically

If you need to store information inside an XML file without losing its contents, you can use the following.

This code allows you to append your data into existing XML elements.

public void StoreToXML()

        {

 

  XmlDocument xdoc = new XmlDocument();

  xdoc.Load(“scores.xml”);

  xdoc.GetElementsByTagName(“Asset”).Item(0).InnerXml =

                           xdoc.GetElementsByTagName(“Asset”).Item(0).InnerXml + “<Player>”+ PlayerName + “</Player><Score>” + Score.ToString() +“</Score>”;

     

          

FileStream fsxml = new FileStream(“scores.xml”,FileMode.Truncate,FileAccess.Write,FileShare.ReadWrite);

          

            // XML Document Saved

            xdoc.Save(fsxml);

            fsxml.Flush();

            fsxml.Close();

         }

For running the above code, You should have an XML file and inside that, you should have the following elements.

<root>

<Asset>

</Asset>

</root>

Ex-Output:

<root>

<Asset>

<Player> NewPlayer </Player>

<Score> NewScore </Score>

</Asset>

</root>

Leave a comment