Tuesday, August 05, 2008

Manipulate XML File Data Using C#

Display Contents of XML File
Listing 1 shows a simple XML file for demonstration:

Listing 1



Mark
Sams



Joe
AWL



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

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

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

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

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

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();