Logo

XML File Processing: Ice Cream Orders

 

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 dteOrder
  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:
    tmeOrder
    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: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
{
	 XmlTextWriter *xtw = new XmlTextWriter(S"exo1.xml", 0);
	 xtw->Formatting = Formatting::Indented;

	 xtw->WriteStartDocument();
	 xtw->WriteStartElement(S"employee");
	 xtw->WriteElementString(S"fullname", this->txtFullName->Text);
	 xtw->WriteElementString(S"department", this->txtDepartment->Text);
	 xtw->WriteElementString(S"salary", this->txtSalary->Text);
	 xtw->WriteElementString(S"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: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
    {
    	 if( saveFileDialog1->ShowDialog() == DialogResult::OK )
    	 {
    		 XmlTextWriter *xtw;
    
    		 try {
    			 xtw = new XmlTextWriter(saveFileDialog1->FileName, 0);
    					 
    			 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(S"custorder");
    			 xtw->WriteElementString(S"orderdate", this->dteOrder->Text);
    			 xtw->WriteElementString(S"ordertime", this->tmeOrder->Text);
    			 xtw->WriteElementString(S"flavor", this->cboFlavors->get_Text());
    			 xtw->WriteElementString(S"container", this->cboContainers->get_Text());
    			 xtw->WriteElementString(S"ingredient", this->cboIngredients->get_Text());
    			 xtw->WriteElementString(S"scoops", iScoop.ToString());
    			 xtw->WriteEndDocument();
    		 }
    		 catch(ArgumentException *AE)
    		 {
    			 MessageBox::Show(String::Concat(S"Error: ", AE->Message, "\n",
    				S"You must provide a name for the file you want to save"));
    		 }
    		 catch(IOException *IOE)
    		 {
    			MessageBox::Show(String::Concat(S"Error: ", IOE->Message, "\n",
    S"You may have entered an invalid character in the name of the file. That is, a character that cannot be accepted"));
    		 }
    		 catch(...)
    		 {
    			 MessageBox::Show(S"The file cannot be save... for some strange reason!");
    		 }
    		 __finally
    		 {
    			 xtw->Close();
    		 }
    	 }
    	 else
    		 MessageBox::Show(S"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: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
{
	 XmlTextWriter *xtw = new XmlTextWriter(S"exo1.xml", 0);
	 xtw->Formatting = Formatting::Indented;

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

	 xtw->Close();
}

private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)
{
	 XmlTextReader *xtr = new XmlTextReader(S"exo1.xml");

	 xtr->ReadStartElement();
	 String *Fln  = xtr->ReadElementString(S"fullname");
	 String *Dpt = xtr->ReadElementString(S"department");
	 String *Slr  = xtr->ReadElementString(S"salary");
	 String *Phn = xtr->ReadElementString(S"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: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)
    {
    	 if( openFileDialog1->ShowDialog() == DialogResult::OK )
    	 {
    		 XmlTextReader *xtr;
    				 
    		 try {
    			 xtr = new XmlTextReader(openFileDialog1->FileName);
    				 	
    			 xtr->ReadStartElement();
    			 String *strOrderDate  = xtr->ReadElementString(S"orderdate");
    			 String *strOrderTime  = xtr->ReadElementString(S"ordertime");
    			 String *strFlavor     = xtr->ReadElementString(S"flavor");
    			 String *strContainer  = xtr->ReadElementString(S"container");
    			 String *strIngredient = xtr->ReadElementString(S"ingredient");
    			 String *strScoops     = xtr->ReadElementString(S"scoops");
    
    			 this->dteOrder->Text = strOrderDate;
    			 this->tmeOrder->Text = strOrderTime;
    			 this->cboFlavors->set_Text(strFlavor);
    			 this->cboContainers->set_Text(strContainer);
    			 this->cboIngredients->set_Text(strIngredient);
    			 if( strScoops->Equals(S"1") )
    				 this->rdoOne->Checked = true;
    			 else if( strScoops->Equals(S"2") )
    				 this->rdoTwo->Checked = true;
    			 else
    				 this->rdoThree->Checked = true;
    		 }
    		 catch(XmlException *XE)
    		 {
    	MessageBox::Show(String::Concat(S"Error: ", XE->Message, "\n", S"The file name you provided is not valid"));
    		 }
    		 catch(...)
    		 {
    			 MessageBox::Show(S"The file cannot be opened... for some strange reason!");
    		 }
    		 __finally
    		 {
    			 xtr->Close();
    		 }
    	 }
    	 else
    		 MessageBox::Show(S"The file was not saved!!!");
    }
  4. Execute the application
  5. Click the Open button and open a previously created record
  6. Close the form to dismiss the application
 

Home Copyright © 2004-2010 FunctionX, Inc.