Logo

XML Applications: Ice Cream

 

File Processing With XML

Introduction

The level of support that the Microsoft .Net Framework provides to XML is amazingly huge. With that library, you can write various types of applications that use XML as their background foundation. Of course, file processing with XML was not neglected. In fact, any application to save and retrieve files or values can use XML as the technique for storing or organizing these values.

There are various classes used to perform file processing in XML. The primary class used to take care of this aspect is XmlSerializer. The XmlTextWriter can be used to create text a basic XML file as text. The XmlTextReader can be used to retrieve the elements of an XML file.

Whenever using one of the XML classes, make sure you call the System.Xml namespace:

using namespace System.Xml;
 

Practical Learning: Introducing XML File Processing

  1. If you want to follow, start Microsoft Visual Studio .Net 2003 or Visual C# .Net 2003
  2. Create a new Windows Forms Application and named it XMLIceCream1
  3. From Solution Explorer, double-click app.ico and change its design as follows:
     
    32x32 16x16

    Here is the form we will use
     

  4. Change the form's Icon to the above app.ico
  5. Set the form's Text to Domba Ice Cream
  6. Set its MaximizeBox to False
  7. Add a GroupBox to the form and change its Text property to Preparation
  8. Add a label inside the group box and set its Text property to Order Date:
  9. Add a DateTimePicker inside the group box
  10. Change its Format property to Short and its Name to dtpDate
  11. Add a label inside the group box and set its Text property to Order Time:
  12. Add a DateTimePicker inside the group box
  13. Change the following properties:
    Format: Time
    Name:
    dtpTime
    ShowUpDown: True
  14. Add a Label in the group box and set its Text to Flavor:
  15. Add a ComboBox inside the group box
  16. Click the ellipsis button of its Items property and create the list with:
     
    Vanilla
    Cream of Cocoa
    Chocolate Chip
    Cherry Coke
    Butter Pecan
    Chocolate Cookie
    Chunky Butter
    Organic Strawberry
    Chocolate Brownies
    Caramel Au Lait
  17. Click OK
  18. Change its  following properties:
    Name: cboFlavors
    Text: Vanilla
  19. Add a Label in the group box and set its Text to Container:
  20. Add a ComboBox inside the group box
  21. Click the ellipsis button of its Items property and create the list with:
     
    Cone
    Cup
    Bowl
  22. Click OK
  23. Change the following properties:
    Name: cboContainers
    Text: Cone
  24. Add a Label in the group box and set its Text to Ingredient:
  25. Add a ComboBox inside the group box
  26. Click the ellipsis button of its Items property and create the list with:
     
    None
    Peanuts
    Mixed Nuts
    M & M
    Cookies
  27. Click OK
  28. Change the following properties:
    Name: cboIngredients
    Text: None
  29. Design the rest of the form with the following controls:
     
    Control Name Text Other Properties
    GroupBox   Number of Scoops  
    RadioButton rdoOne One CheckAlign: MiddleRight
    Checked: True
    RadioButton rdoTwo Two CheckAlign: MiddleRight
    RadioButton rdoThree Three CheckAlign: MiddleRight
    GroupBox   Order Processing  
    Label   Order Total:  
    TextBox txtOrderTotal   TextAlign: Right
    Button btnSave Save  
    Button btnOpen Open  
    Button btnClose Close  
  30. Save All

Creating an XML File

Many of the XML files you will use would either have been created manually from a text editor such as Notepad or would have been generated from an application. It is also possible to let the user save a file as XML. When you do this, the file would be formatted as a normally XML file.

To start, you can declare a pointer to XmlTextWriter. One of its constructors allows you to specify the name of the file being saved and the type of encoding used. The syntax of this constructor is:

public XmlTextWriter(string filename,   Encoding encoding);

The first argument is the name of the file you want to use. The second argument is the type of encoding used. If you pass it as 0, the UTF-8 encoding would be used.

After instantiating the class, you can create each element of the file. Once again you have various options. the easiest way to create an element is by using the WriteElementString() method derived from the XmlWriter parent class.

After using the XML class, you can close it by calling its Close() method. Here is an example of using the XmlTextWriter to save a file as XML:

 

private void button1_Click(object   sender, System.EventArgs  e)
	{
		 XmlTextWriter xtw = new XmlTextWriter("exo1.xml", Encoding.UTF8);
		 xtw.Formatting = Formatting.Indented;

		 xtw.WriteStartDocument();
		 xtw.WriteStartElement("employee");
		 xtw.WriteElementString("fullname", this.txtFullName.Text);
		 xtw.WriteElementString("department", this.txtDepartment.Text);
		 xtw.WriteElementString("salary", this.txtSalary.Text);
		 xtw.WriteElementString("phonenumber", this.txtPhoneNumber.Text);
		 xtw.WriteEndDocument();

		 xtw.Close();
	 }

Practical Learning: Saving a File as XML

  1. Add a SaveFileDialog1 to the form
  2. Set its Filter to Ice Cream Orders (*.xml)|*.xml|Text files (*.txt)|*.txt|All files (*.*)|*.*"
  3. On the form, double-click the Save button and implement its Click event as follows:
      
    private void btnSave_Click(object sender, System.EventArgs e)
    {
    	if( this.saveFileDialog1.ShowDialog() == DialogResult.OK )
    	{
    		XmlTextWriter xtw = null;
    				
    		try 
    		{
    			xtw = new XmlTextWriter(this.saveFileDialog1.FileName, Encoding.UTF8);
    			xtw.Formatting = Formatting.Indented;
    			int iScoop;
    
    			if( this.rdoOne.Checked == true )
    				iScoop = 1;
    			else if( this.rdoTwo.Checked == true )
    				iScoop = 2;
    			else
    				iScoop = 3;
    
    			xtw.WriteStartDocument();
    			xtw.WriteStartElement("custorder");
    			xtw.WriteElementString("orderdate", this.dtpDate.Text);
    			xtw.WriteElementString("ordertime", this.dtpTime.Text);
    			xtw.WriteElementString("flavor", this.cboFlavors.Text);
    			xtw.WriteElementString("container", this.cboContainers.Text);
    			xtw.WriteElementString("ingredient", this.cboIngredients.Text);
    			xtw.WriteElementString("scoop", iScoop.ToString());
    		}
    		catch(ArgumentException AE)
    		{
    			MessageBox.Show("Error: " + AE.Message);
    		}
    		catch(InvalidOperationException ioe)
    		{
    			MessageBox.Show("Error: " + ioe.Message);
    		}
    		finally
    		{
    			xtw.Close();
    		}
    	}
    	else
    		MessageBox.Show("The file was not saved");
    }
  4. Execute the application (Ctrl + F5) and enter a record:
     
  5. Click the Save button. Name the file icebaby1 and make sure the file type is set to XML
     
  6. Click Save
  7. Close the form

Reading an XML File

If an XML file has already been created, either by you or someone else, you can read its elements and process them as you wish. Once again, there are various options. While creating a file can be significantly easier because you are the one who would start the process and can arrange it anyway you like, reading an XML file can involve many more issues because you are likely to deal with a file that was created by someone else and probably using a different understanding or arrangement than yours. Nevertheless, you should be able to read any XML file regardless of who created and how it was created, as long as it is "well-formed".

One of the easiest ways to retrieve the elements of an XML is through the XmlTextreader class. This class provides so many constructors (when was the last time you saw a class with 14 constructors?). The default constructor allows you to start the XML file without specifying its details. Another constructor provides a counterpart to the XmlTextWriter constructor we used above. This one takes only a string as the name of the file to be opened. Its syntax is:

public XmlTextReader(string url);

After declaring a variable for the file, you can ReadElementString() method to retrieve the value of the desired element. This method, derived from the XmlReader class, is overloaded with three versions. One of the versions takes a String as argument. Its syntax is:

public virtual string ReadElementString(string name);

The argument is the name of the element. This method returns a the value of the element or empty if the element is empty. Here is an example:

private void button1_Click(object  sender, System.EventArgs  e)
	{
		 XmlTextWriter xtw = new XmlTextWriter("exo1.xml", Encoding.UTF8);
		 xtw.Formatting = Formatting.Indented;

		 xtw.WriteStartDocument();
		 xtw.WriteStartElement("employee");
		 xtw.WriteElementString("fullname", this.txtFullName.Text);
		 xtw.WriteElementString("department", this.txtDepartment.Text);
		 xtw.WriteElementString("salary", this.txtSalary.Text);
		 xtw.WriteElementString("phonenumber", this.txtPhoneNumber.Text);
		 xtw.WriteEndDocument();

		 xtw.Close();
	 }

private void button2_Click(object  sender, System.EventArgs e)
	 {
		 XmlTextReader xtr = new XmlTextReader("exo1.xml");

		 xtr.ReadStartElement();
		 string Fln  = xtr.ReadElementString("fullname");
		 string Dpt = xtr.ReadElementString("department");
		 string Slr  = xtr.ReadElementString("salary");
		 string Phn = xtr.ReadElementString("phonenumber");

		 this.txtFullName.Text   = Fln;
		 this.txtDepartment.Text = Dpt;
                 this.txtSalary.Text     = Slr;
		 this.txtPhoneNumber.Text= Phn;

		 xtr.Close();
	 }

Practical Learning: Opening an XML File

  1. Add an OpenFileDialog to the form
  2. Set its Filter to Ice Cream Orders (*.xml)|*.xml|Text files (*.txt)|*.txt|All files (*.*)|*.*"
  3. On the form, double-click the Open button and implement its Click event as follows:
    private void btnOpen_Click(object sender, System.EventArgs e)
    {
    	if( openFileDialog1.ShowDialog() == DialogResult.OK )
    	{
    	    XmlTextReader xtr = null;
    				
    	    try {
    		xtr = new XmlTextReader(openFileDialog1.FileName);
    				 	
    		xtr.ReadStartElement();
    	       string strOrderDate  = xtr.ReadElementString("orderdate");
    	       string strOrderTime  = xtr.ReadElementString("ordertime");
    	        string strFlavor     = xtr.ReadElementString("flavor");
    	       string strContainer  = xtr.ReadElementString("container");
    	      string strIngredient = xtr.ReadElementString("ingredient");
    	        string strScoops     = xtr.ReadElementString("scoops");
    
    		this.dtpDate.Text = strOrderDate;
    		this.dtpTime.Text = strOrderTime;
    		this.cboFlavors.Text = strFlavor;
    		this.cboContainers.Text = strContainer;
    		this.cboIngredients.Text = strIngredient;
    		if( strScoops.Equals("1") )
    		    this.rdoOne.Checked = true;
    		else if( strScoops.Equals("2") )
    		   this.rdoTwo.Checked = true;
    		else
    		   this.rdoThree.Checked = true;
    	    }
    	    catch(XmlException XE)
    	    {
                   MessageBox.Show("Error: " + XE.Message);
    	    }
    	    finally
    	    {
    		   xtr.Close();
    	    }
        }
        else
    	   MessageBox.Show("The file was not saved!!!");
    }
  4. Double-click the Close button and implement it as follows:
    private void btnClose_Click(object sender, System.EventArgs e)
    {
    	Close();
    }
  5. Execute the application
  6. Click the Open button and open a previously created record
  7. Close the form to dismiss the application
 

Home Copyright © 2004-2010 FunctionX, Inc.