Quick Tip: Read and Parse XML File With C#
Submitted by whiztech on Sun, 08/09/2009 - 03:43
While I was developing My Timer 0.1.0 beta 1, the hardest part for me to solve is how to parse the stored configuration file (which is in XML format) and read the values. It took me almost 2 days to figure out the best way to parse the XML file (at least it works for me). You can take a look at my example so you will have the idea to develop your own XML parser. The code is a bit long even though it only do a small task. I'll try my best to explain the code, if you have any questions feel free to drop a comment.
Our mission is to read and parse this XML file and output the data to the console application.
XML file: Students.xml
<School> <Student> <Name>Hussin Samad</Name> <Sex>Male</Sex> <DOB Day="10" Month="April" Year="1995" /> <Address>Lot 1000, Kg Raja, 22200 Besut, Terengganu, Malaysia</Address> <Email>hussin.samad@yahoo.co.uk</Email> <Phone>+60179245230</Phone> </Student> <Student> <Name>Mack W. Ramirez</Name> <Sex>Male</Sex> <DOB Day="15" Month="September" Year="1985" /> <Address>2804 Stout Street York, PA 17401</Address> <Email>MackWRamirez@text2re.com</Email> <Phone>717-350-2488</Phone> </Student> <Student> <Name>Mikako Arata</Name> <Sex>Female</Sex> <DOB Day="31" Month="October" Year="1986" /> <Address>Alpenstrasse 6, 5121 STEINBACH</Address> <Email>MikakoArata@text2re.com</Email> <Phone>570-724-1172</Phone> </Student> <Student> <DOB Day="23" Month="November" Year="1991" /> <Name>Dionisia Genovesi</Name> <Sex>Female</Sex> <Email>DionisiaGenovesi@text2re.com</Email> <Phone>406-554-8874</Phone> <Address>559 Masonic Drive, North Broadus, MT 59317</Address> </Student> </School>
As you can see from the XML file, we have a data of 4 students. We have the students' names, gender, date of birth, addresses, e-mails and phone numbers. "Name", "Sex", "Address", "Email" and "Phone" elements have text content and "DOB" element has "Day", "Month" and "Year" attributes. We will now try to read the XML file and output the data to the screen. Here is the sample C# console application code:
using System;
using System.Xml;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string handle = "";
int StudentCount = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
settings.IgnoreProcessingInstructions = true;
XmlReader reader = XmlReader.Create("Students.xml", settings);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
switch (reader.Name)
{
case "Student":
StudentCount++;
Console.WriteLine("--------------------------------");
Console.WriteLine("Student number: " + StudentCount);
break;
case "Name":
handle = "Name";
break;
case "Sex":
handle = "Sex";
break;
case "DOB":
Console.Write("Date of Birth: ");
Console.Write(reader.GetAttribute("Day") + " ");
Console.Write(reader.GetAttribute("Month") + " ");
Console.WriteLine(reader.GetAttribute("Year"));
break;
case "Address":
handle = "Address";
break;
case "Email":
handle = "Email";
break;
case "Phone":
handle = "Phone";
break;
default:
handle = "";
break;
}
// break XmlNodeType.Element
break;
case XmlNodeType.Text:
switch (handle)
{
case "Name":
Console.WriteLine("Name: " + reader.Value);
break;
case "Sex":
Console.WriteLine("Gender: " + reader.Value);
break;
case "Address":
Console.WriteLine("Address: " + reader.Value);
break;
case "Email":
Console.WriteLine("E-mail: " + reader.Value);
break;
case "Phone":
Console.WriteLine("Phone: " + reader.Value);
break;
}
// break XmlNodeType.Text
break;
}
}
Console.ReadLine();
}
}
}
After you compiled the code, you will get this simple output:
Source code explanation:
1. Line 2:
1. Line 2:
using System.Xml;
We need to include the 'System.Xml' namespace in order to use 'XmlReader'.
2. Line 13:
XmlReaderSettings settings = new XmlReaderSettings();
Create a new 'XmlReaderSettings' instance to be used with our 'XmlReader'.
3. Line 14 to 16:
settings.IgnoreWhitespace = true; settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true;
We will set our 'XmlReader' to ignore insignificant white space, comments and processing instructions.
4. Line 18:
XmlReader reader = XmlReader.Create("Students.xml", settings);Create a new 'XmlReader' using configuration from 'settings' and open 'Students.xml' for read.
5. Line 20:
while (reader.Read())
Read the Xml file until there is no more nodes to be read.
6. Line 22:
switch (reader.NodeType)
Line 24:
case XmlNodeType.Element:
Line 78:
case XmlNodeType.Text:
We will check the type of node that being read by 'XmlReader'. Example of 'XmlNodeType.Element' is '<Name>' or '<Address>'. 'XmlNodeType.Text' is the text content inside of an element, for example, in '<Name>Hussin Samad</Name>', Hussin Samad is the text content of element 'Name'.
7. Line 26 to 73:
Before the text value of an element is being read, we will first set the variable 'handle' with proper value so we can know the element which own the text content that we will read later.
8. Line 47 to 49:
Console.Write(reader.GetAttribute("Day") + " ");
Console.Write(reader.GetAttribute("Month") + " ");
Console.WriteLine(reader.GetAttribute("Year"));Since the element "DOB" contains attribute, we will use GetAttribute function to read the value from 'Day', 'Month' and 'Year'.
9. Line 80 to 106:
Read the text value and output it to the screen with proper title.
I hope you find this post useful. Feel free to drop comments. The full source code is available for download (the 'Students.xml' file is in \bin\Debug folder).
[Download: ConsoleApplication2.zip (24.2KB)]
Tags:
Cannot find what you are looking for?
Similar entries
- HandyCafe - Internet Cafe Software: Block HandyCafe Popup
- How to Save a Website/Webpage To PDF
- How to Convert PDF files to DOC (Word Document)
- Enable GodMode (Useful Centralized System Settings) on Windows 7 / Vista
- Creating a Shortcut to Quickly Shutdown or Restart Windows
- How to Batch Resize or Convert Multiple Images Easily
- Creating .tar.gz Archive Easily in Windows



