Manipulate XML File Data Using C#

Nearly 95 percent of .NET applications use XML for various tasks. A main usage for Web developers is combining XML with HTML to display information on Web pages, which relieves them from having to spend a long time editing the content on their Web pages. A single change to an XML file will be reflected across the entire Web site, thus simplifying the development and also greatly reducing the development time.

With the advent of .NET, programming languages such as C#, Visual Basic .NET, and frameworks such as ASP.NET took advantage of XML's rich features. In fact, the configuration file (web.config), which is used in ASP.NET applications, is completely built upon XML tags.

This article demonstrates how to manipulate an XML file using C#. The manipulation includes displaying, adding, editing, and deleting data from a single XML file using C#. It also shows how to use the Stream class included in the System.IO namespace and various other XML classes included in the System.XML namespace.

Display Contents of XML File

Listing 1 shows a simple XML file for demonstration:

Listing 1

<?xml version="1.0"?>
<Books>
  <Book ID="001">
    <Author>Mark</Author>
    <Publisher>Sams</Publisher>
  </Book>

  <Book ID="002">
    <Author>Joe</Author>
    <Publisher>AWL</Publisher>
  </Book>
</Books>

To test the above XML file for errors, simply open it with your browser. If it has no errors, the file will be displayed as such.

The next step is to display all the data using a C# console application (see Listing 2).

Listing 2: DisplayCatalog.cs

XmlNodeList xmlnode = xmldoc.GetElementsByTagName("Book");
   Console.WriteLine("Here is the list of catalogs\n\n");

   for(int i=0;i<xmlnode.Count;i++)
   {
   XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

   //XML Attribute Name and Value returned
   //Example: <Book id = "001">

   Console.Write(xmlattrc[0].Name);
   Console.WriteLine(":\t"+xmlattrc[0].Value);

   //First Child of the XML file - Catalog.xml - returned
   //Example: <Author>Mark</Author>

   Console.Write(xmlnode[i].FirstChild.Name);
   Console.WriteLine(":\t"+xmlnode[i].FirstChild.InnerText);

   //Last Child of the XML file - Catalog.xml - returned
   //Example: <Publisher>Sams</Publisher>

   Console.Write(xmlnode[i].LastChild.Name);
   Console.WriteLine(":\t"+xmlnode[i].LastChild.InnerText);
   Console.WriteLine();

Listing 2 is just an extract from the DisplayCatalog() method of the C# application. It displays the data from the XML file. It uses the XMLNodeList class to retrieve the relevant XML node and then iterates it with the help of the for loop and the Count property of the class. Inside the loop, it creates an instance of the XMLAttributeCollection class and displays the appropriate values using the properties of the class.

Inside the constructor, the code creates an instance of the FileStream class and sets the required permissions (see Listing 3). It then loads the XML document with the help of the XMLDocument class and loads the required instance of the FileStream class with the Load() method of the XMLDocument class.

Listing 3: DisplayCatalog.cs

FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read,
                               FileShare.ReadWrite);
   xmldoc = new XmlDocument();
   xmldoc.Load(fs);
   DisplayCatalog();
You can download the complete source code for all the from the code download section at the end of this article.

The final output looks like the display in Figure 1.

Figure 1: Final Output from Listings 2 and 3

The above walkthrough showed how to display the contents of an XML file using a C# program. The next section demonstrates how to write data directly to the XML file using a C# console application.

Write Data Directly to XML File

Listing 4 appends a new catalog entry to the XML document using the various properties and methods of the XMLDocument class.

Listing 4: AddCatalog.cs

// New XML Element Created
XmlElement newcatalogentry = xmldoc.CreateElement("Book");

// New Attribute Created
XmlAttribute newcatalogattr = xmldoc.CreateAttribute("ID");

// Value given for the new attribute
newcatalogattr.Value = "005";

// Attach the attribute to the XML element
newcatalogentry.SetAttributeNode(newcatalogattr);

// First Element - Book - Created
XmlElement firstelement = xmldoc.CreateElement("Book");

// Value given for the first element
firstelement.InnerText = "Peter";

// Append the newly created element as a child element
newcatalogentry.AppendChild(firstelement);


// Second Element - Publisher - Created
XmlElement secondelement = xmldoc.CreateElement("Publisher");

// Value given for the second element
secondelement.InnerText = "Que Publishing";

// Append the newly created element as a child element
newcatalogentry.AppendChild(secondelement);

// New XML element inserted into the document
xmldoc.DocumentElement.InsertAfter(newcatalogentry,
                                   xmldoc.DocumentElement.LastChild);

// An instance of FileStream class created
// The first parameter is the path to the XML file - Catalog.xml

FileStream fsxml = new FileStream(path,FileMode.Truncate,
                                  FileAccess.Write,
                                  FileShare.ReadWrite);

// XML Document Saved
xmldoc.Save(fsxml);

Manipulate XML File Data Using C#

Initially, it creates a new XML element and attribute. It then attaches the attribute 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.

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

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.

[Anand2.jpg]

Figure 2: InsertAfter() Method in Action

[Anand3.jpg]

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#.



About the Author

Anand Narayanaswamy

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds