February 17, 2019
Hot Topics:

Manipulate XML File Data Using C#

  • March 14, 2005
  • By Anand Narayanaswamy
  • Send Email »
  • More Articles »

The listing initially creates a new XML element and attribute. The attribute is then attached to the XML element with the help of the SetAttributeNode method. Next, it creates the first and second elements and supplies the required values by using the InnerText property. It then appends the newly created elements to the XML file by using the AppendChild method. After this process is complete, it inserts the new XML element into the file with the help of appropriate methods.

Refer to the .NET Framework documentation for more details. A complete discussion regarding the System.XML namespace is beyond the scope of this article.

As you can see from the above code, the new child node gets inserted after the last child node. It can be added before the last child node using the InsertBefore method of the XMLDocument class. Finally, an instance of the FileStream class is created and the document is saved using the Save() method of the XMLDocument class.

If you run the above program, you will see only a message that the data has been successfully added to the XML file. To verify whether the data really has been added, you should open the relevant XML file. Figures 2 and 3 show snapshots of the XML file after the data has been added using the InsertAfter() and InsertBefore() methods as discussed above.

Figure 2: InsertAfter() Method in Action

Figure 3: InsertBefore() Method in Action

Apply Techniques to WinForms

You have learned how to display and add data to an XML file using C# console applications. With a little effort, you can implement these techniques in Windows-based applications (WinForms). The next article will demonstrate how to edit and delete data from an XML file using C#.

Download the Code

To download the accompanying source code for this article, click here.

About the Author

Anand Narayanaswamy (Microsoft MVP) works as an independent consultant and runs NetAns Technologies (www.netans.com), which provides affordable and reliable Web hosting services for the community. He also runs Webhostinghotel.com, which provides affordable ASP.NET, SQL Server hosting services for developers. Anand also runs LearnXpress.com, Dotnetalbum.com, and Csharpfaq.com, and regularly contributes articles, product reviews, and book reviews for various Web sites. He can be reached at ananddotnet@yahoo.co.in.

Page 2 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date