ARTICLE

Methods for Transforming data to a XML file

Posted by Lalitha Venkatasubramanian Articles | ADO.NET May 16, 2006
This articles mentions different ways to tranform data to XML file.
Reader Level:
Download Files:
 

Here are the different methods to transform a data file to a XML Document:

 

Method 1:

 

The first idea of converting a piece of data which are in a text files to a Xml Document is by using a DataSet. By using a DataSet, we can bind that data to the DataGrid and do the updation, deletion and addition operations. Even though the final output is the same Xml file, we have the Dataset in between to manipulate the data.

 

Example:

 

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Xml;

using System.IO;

 

namespace XMLWork1

{ 

      /// <summary>

      /// Summary description for WebForm1.

      /// </summary>

      public class WebForm1 : System.Web.UI.Page

      {

            protected System.Web.UI.WebControls.Label Label1;

            protected System.Web.UI.WebControls.Label Label2;

            protected System.Web.UI.WebControls.TextBox txtName;

            protected System.Web.UI.WebControls.TextBox txtPlace;

            protected System.Web.UI.WebControls.Button Fill;

            DataSet dataSet=new DataSet ("dataSet");

            DataTable dt=new DataTable ();

            protected System.Web.UI.WebControls.DataGrid DataGrid1;

            DataRow dr;

     

            private void Page_Load(object sender, System.EventArgs e)

            {

                  if(!IsPostBack)

                  {

                        try

                        {

                              dataSet.ReadXml(Server.MapPath ("sample.xml"));

                        }

                        catch(Exception ex)

                        {

                              if(dataSet.Tables.Count==0)

                              {

                                    dataSet.WriteXml(Server.MapPath ("sample.xml"));

                              }

                              Response.Write (ex.Message);

                        }                    

                  }                

            } 

        

            #region Web Form Designer generated code

            override protected void OnInit(EventArgs e)

            {

                  //

                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.

                  //

                  InitializeComponent();

                  base.OnInit(e);

            }

           

            /// <summary>

            /// Required method for Designer support - do not modify

            /// the contents of this method with the code editor.

            /// </summary>

            private void InitializeComponent()

            {   

                  this.Fill.Click += new System.EventHandler(this.Fill_Click);

                  this.Load += new System.EventHandler(this.Page_Load);

 

            }

            #endregion

 

            private void Fill_Click(object sender, System.EventArgs e)

            {                

                  dataSet.ReadXml(Server.MapPath ("sample.xml"));

                  if(dataSet.Tables.Count==0)

                  {

                        DataColumn dc1=new DataColumn ("Name");

                        DataColumn dc2=new DataColumn ("Place");

                        dataSet.Tables.Add(dt);

                        dataSet.Tables[0].Columns.Add(dc1);

                        dataSet.Tables[0].Columns.Add(dc2);

                  }

                  dr = dataSet.Tables[0].NewRow();

                  dr["Name"]=txtName.Text;

                  dr["Place"]=txtPlace.Text;

                  dataSet.Tables[0].Rows.Add(dr);

                  dataSet.AcceptChanges();

                  dataSet.WriteXml(Server.MapPath("sample.xml"));

                  BindData();                 

            }

            private void BindData()

            {

                  DataGrid1.DataSource = dataSet;

                  DataGrid1.DataBind();

            } 

      }

} 

 

Here in this, on the load method, we are reading the xml file which is created using a DataSet. If it is not getting created it is been catched and it is created. When the Fill Button in the form is clicked after entering the values - Name and Place, a new row is been created and a xml file is generated using the DataSet.WriteXml method. The DataTable, DataColumn, DataRow are used for this purposes.

 

Then for binding the DataGrid, we use the DataGird.DataSource =the dataset.

 

Method 2:

 

The second method is to use the XmlDocument. This class uses the xmlTextWriter and using that the xmlfile is obtained.

 

Example:

 

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Xml;

 

namespace XMLData

{ 

      /// <summary>

      /// Summary description for WebForm1.

      /// </summary>

      public class WebForm1 : System.Web.UI.Page

      {

            protected System.Web.UI.WebControls.DataGrid DataGrid1;

            protected System.Web.UI.WebControls.Button Fill;

            protected System.Web.UI.WebControls.TextBox txtPlace;

            protected System.Web.UI.WebControls.TextBox txtName;

            protected System.Web.UI.WebControls.Label Label2;

            protected System.Web.UI.WebControls.Label Label1;

             

            private void Page_Load(object sender, System.EventArgs e)

            {

                  if(!IsPostBack)

                  {

                        // Put user code to initialize the page here

                  }

            } 

       

            #region Web Form Designer generated code

            override protected void OnInit(EventArgs e)

            {

                  //

                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.

                  //

                  InitializeComponent();

                  base.OnInit(e);

            }

           

            /// <summary>

            /// Required method for Designer support - do not modify

            /// the contents of this method with the code editor.

            /// </summary>

            private void InitializeComponent()

            {   

                  this.Fill.Click += new System.EventHandler(this.Fill_Click);

                  this.DataGrid1.SelectedIndexChanged += new System.EventHandler(this.DataGrid1_SelectedIndexChanged);

                  this.Load += new System.EventHandler(this.Page_Load);

 

            }

            #endregion

 

            private void Fill_Click(object sender, System.EventArgs e)

            {

                  try

                  {

                        string filename = Server.MapPath("sample2.xml");

                        XmlDocument xmlDoc = new XmlDocument();

                        try

                        {

                              xmlDoc.Load(filename);

                        }

                        catch(System.IO.FileNotFoundException)

                        {

                              //if file is not found, create a new xml file

                              XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);

                              xmlWriter.Formatting = Formatting.Indented;

                              xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");

                              xmlWriter.WriteStartElement("Root");

                              //If WriteProcessingInstruction is used as above,

                              //Do not use WriteEndElement() here

                              //xmlWriter.WriteEndElement();

                              //it will cause the <Root></Root> to be <Root />

                              xmlWriter.Close();

                              xmlDoc.Load(filename);

                        }

                 

                        XmlNode root = xmlDoc.DocumentElement;

                        XmlElement childNode = xmlDoc.CreateElement("Employee");;

                        root.AppendChild(childNode);

                       

                              XmlElement childNode2 = xmlDoc.CreateElement("Name");

                              XmlText textNode1 = xmlDoc.CreateTextNode(txtName.Text);

                              childNode2.AppendChild(textNode1);

                              childNode.AppendChild(childNode2);

 

                              XmlElement childNode3=xmlDoc.CreateElement("Place");

                              XmlText textNode2 = xmlDoc.CreateTextNode(txtPlace.Text);

                              childNode3.AppendChild(textNode2);

                              childNode.AppendChild(childNode3);

                              xmlDoc.Save(filename);

                  }

                  catch(Exception ex)

                  {

                        Response.Write(ex.ToString());

                  }

 

            }          

      }

}

 

The main point to be noted here is that we are not using any dataset here. Both the two methods use and produce the same xml file as output. But the difference is that, we cannot bind it to a DataGrid as we are not using any DataSets to be indulged in this. There are many other methods also ie., by using XMLDataDocument also.

COMMENT USING
Employers - Post Free Jobs