perfectxml.com
 Basic Search  Advanced Search   
Topics Resources Free Library Software XML News About Us
  You are here: home Info Bank Articles » XML Data Manipulation in C# Using DataSet Class Saturday, 23 February 2008
 

Back to Articles Page      

        

XML Data Manipulation in C# Using DataSet Class


  • Introduction
    ADO.NET, a major upgrade to ADO introduced some nice architectural enhancemenets. DataSet class, an alternative to disconnected recordsets, is an example of these upgrades. The DataSet class is useful to hold chunks of data read from the database. The in-memory cache for DataSet consist of tables, relationships and constraints. In this short article, I'll illustrate use of DataSet class first to read an XML data file and then we'll add one record to the data file. Note that in this article we are working with data stored in an XML file, however you could very well use DataSet class with the database. Interestingly DataSet in turn reads and writes data and schema as XML documents.

    The DataSet class resides in System.Data namespace and is available in System.Data.dll assembly. Following are the DataSet class methods useful to read and write XML data:

    Read Method Write Method Description
    ReadXml WriteXml Reads/Writes XML schema and data into the DataSet.
    ReadXmlData WriteXmlData Used to read/write only XML data.
    ReadXmlSchema WriteXmlSchema Used to read/write only XML schema.


    Every table within a DataSet object is represented by a DataTable object; every column within a DataTable is represented by a DataColumn object; & every row within a DataTable is represented by a DataRow object.


  • A Simple Example
    Let's now look at a simple example to first read from and then write data stored in an XML document. The sample XML data and schema files can be extracted from the source code zip file (see end of this article to download the zip file) accompanied with this article.

    I'll use my preferred language, C#, to write code; and csc.exe to compile the code from the DOS command prompt. To build and run the sample, you'll need Microsoft .NET Framework SDK installed.

    /*
    XmlDataSet.cs
    Compile: csc /r:System.dll;System.Data.dll;System.Xml.dll XmlDataSet.cs
    */

    using System;
    using System.Data;
    using System.IO;
    public class XmlDataSet
    {
       public static void Main()
       {
          //Create a DataSet object
          DataSet ds = new DataSet();

          //Create a FileStream to the XML Schema file in Read mode
          FileStream finschema = new FileStream("userdata.xsd",FileMode.Open,
                                 FileAccess.Read,FileShare.Read);

          //Read the Schema into the DataSet
          ds.ReadXmlSchema(finschema);

          //Close the FileStream
          finschema.Close();

          //Create a FileStream to the Xml Database file in Read mode
          FileStream findata = new FileStream("userdata.xml", FileMode.Open,
                               FileAccess.Read,FileShare.ReadWrite);

          //Read the DataBase into the DataSet
          ds.ReadXmlData(findata);

          //Close the FileStream
          findata.Close();

          Console.WriteLine("Welcome to the Users List Program");
          Console.WriteLine("List of all Users") ;

          //Loop through each row within the DataSet

          foreach(DataRow dr in ds.Tables[0].Rows)
          {
                Console.WriteLine();

                //Display the contents of the column firstname
                Console.WriteLine(dr["firstname"]);

                //Display the contents of the column lastname
                Console.WriteLine(dr["lastname"]);

          }


          //create a new DataRow object containing the table schema
          //from the DataSet
          DataRow newrow = ds.Tables[0].NewRow();

          Console.WriteLine();
          Console.WriteLine("Add new user to the List");
          Console.Write("Enter the First Name :");

          //Take the input from the user and store it into the DataRow
          newrow["firstname"] = Console.ReadLine();
          Console.Write("Enter the Last Name :") ;

          //Store the Last Name into the lastname column
          newrow["lastname"] = Console.ReadLine();

          //Add the updated DataRow into the DataSet
          ds.Tables[0].Rows.Add(newrow);

          Console.WriteLine();
          Console.WriteLine("Updating Database file");

          //Open a FileStream to the Database in Write Mode
          FileStream fout = new FileStream("userdata.xml",FileMode.OpenOrCreate,
                         FileAccess.Write,FileShare.ReadWrite);

          //Write the XML data to the stream
          ds.WriteXmlData(fout);

          //Close the Stream
          fout.Close();
          Console.WriteLine("Database Updated!");
          Console.WriteLine();
          Console.WriteLine("Press Enter to Exit");
          Console.ReadLine();
       }
    }



    The above code begins with creating an instance of DataSet class and then loading that DataSet object with XML Schema and data with the help of FileStream objects and DataSet's ReadXmlSchema and ReadXmlData methods. A for loop then iterates over each XML data row and prints it out to the console. Next, we create an instance of DataRow class by calling NewRow method of DataTable class. We fill the DataRow object by accepting the values from the user and finally to persist this new record we use FileStream in conjunction with DataTable's Add and DataSet's WriteXmlData methods.

    The output should look like:
    Output





  • Summary
    With the help of few lines of C# code, this article illustrated how you can use DataSet class to read and write XML data. Go ahead and download the sample code (along with sample XML data and schema files) and try out above example yourself! I hope you enjoyed this short article, if you have any questions or comments, feel free to forward them to me at saurabhn@webveda.com  E-mail .


Download sample source code files.
If you have any questions or comments, feel free to contact author of this article, Saurabh Nandu at saurabhn@webveda.com  E-mail .

  

Back to Articles Page      

All information on this site is for training only. We do not warrant its correctness or its fitness to be used. The risk of using it remains entirely with the user. 

 

  Contact Us | E-mail Us | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy