Using XML with Datasets

Using XML with Datasets

XML can also be used with datasets. The DataSet class, described in Chapter 18, has methods for both reading and writing XML. In this section, you’ll learn how to place XML data in a dataset and how to write data from a dataset to an XML file.

Placing XML Data into a Dataset

To read data into a dataset, you use the ReadXml method of the DataSet class. This method can work with both XML and schema information. Consider the following XML file, which is like the one that was created using the Videos form presented earlier in this chapter, in the section “Sample Application Using XmlTextWriter”:

<?xml version="1.0" encoding="utf-8" ?>
<!--Video Library-->
<!--This is a file containing a number of videos.-->
<VideoLibrary>
   <Video>
      <Title>Gone with the Wind</Title>
      <Length Measurement="minutes">111</Length>
      <star>Clark Gable</star>
      <rating>PG</rating>
   </Video>
   <Video>
      <Title>The Matrix</Title>
      <Length Measurement="minutes">123</Length>
      <star>Keanu Reeves</star>
      <rating>R</rating>
   </Video>
   <Video>
      <Title>Vanilla Sky</Title>
      <Length Measurement="minutes">109</Length>
      <star>Tom Cruise</star>
      <rating>R</rating>
   </Video>
   <Video>
      <Title>Lord of the Rings</Title>
      <Length Measurement="minutes">168</Length>
      <star>Frodo</star>
      <rating>PG-13</rating>
   </Video>
   <Video>
      <Title>Winnie the Pooh</Title>
      <Length Measurement="minutes">93</Length>
      <star>Christopher Robin</star>
      <rating>G</rating>
   </Video>
</VideoLibrary>

The listing for XMLWrite was hard-coded to store an XML file such as the preceding one at C:\Videos.xml. To read this file into a dataset, you should first instantiate a DataSet object, as shown here:

DataSet myDataSet = new DataSet();

After the object has been instantiated, you use the ReadXml method to load the XML data into the dataset, as follows:

myDataSet.ReadXml(@"C:\Videos.xml");

Once this command has been executed, the XML file is loaded into the dataset. You can then manipulate the data just as you can other data stored in a dataset. Refer to Chapter 18 for more information about working with datasets.

The following listing presents a simple form that contains a data grid that displays the primary data in the Videos.xml file:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace ReadDataSet
{
    /// <summary>
    /// Summary description for Form1
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.DataGrid dataGrid1;
        /// <summary>
        /// Required designer variable
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            // TODO: Add constructor code after InitializeComponent call.
         
            // Create the DataSet object. 
            DataSet myDataSet = new DataSet();

            // Load XML data.
            myDataSet.ReadXml(@"C:\Videos.xml");

            // Bind the dataset to the data grid. 
            dataGrid1.DataSource = myDataSet;
            dataGrid1.SetDataBinding(myDataSet, "Video" );
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGrid1 = new System.Windows.Forms.DataGrid();
            ((System.ComponentModel.ISupportInitialize)
                (this.dataGrid1)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGrid1
            // 
            this.dataGrid1.DataMember = "";
            this.dataGrid1.HeaderForeColor = 
                System.Drawing.SystemColors.ControlText;
            this.dataGrid1.Location = new System.Drawing.Point(16, 16);
            this.dataGrid1.Name = "dataGrid1";
            this.dataGrid1.Size = new System.Drawing.Size(496, 232);
            this.dataGrid1.TabIndex = 0;
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(528, 262);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                this.dataGrid1});
            this.Name = "Form1";
            this.Text = "Read Data Set";
            ((System.ComponentModel.ISupportInitialize)
                (this.dataGrid1)).EndInit();
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// Main entry point for the application
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }
    }
}

As you can see, the Videos.xml file is loaded into myDataSet using the ReadXml method. The next two lines of the listing connect the dataset to the data grid and specify which data will be displayed, as follows:

dataGrid1.DataSource = myDataSet;
dataGrid1.SetDataBinding(myDataSet, "Video");

In this case, the video information is displayed. The first line sets the data source for the data grid to the dataset you loaded with the XML data. The second line binds the Video data to the control. This binding will cause the Video data to be displayed as a table.

You can also display the video length information if you change the preceding data binding line to this:

dataGrid1.SetDataBinding(myDataSet, "Length" );

When the Videos.xml file was loaded, it was automatically broken into relational tables for you. You’ll need to write the necessary code if you want to rejoin these tables when displaying the information.

Writing XML from a Dataset

Once you have data in a dataset, you can write it to an XML file by calling the WriteXml method. The WriteXml method of the dataset will take care of all the work for you. The following line of code will create a file named NewXml.xml from myDataSet in the root directory of the C drive:

myDataSet.WriteXml(@"C:\NewXml.xml");

You can also specify whether a schema should be included with the file. This is done by including an XmlWriteMode value as a second parameter to the WriteXml method call, as shown here:

myDataSet.WriteXml(@"C:\Filename", writeMode)

The writeMode parameter can be one of the following values:

  • XmlWriteMode.DiffGram  Writes the XML file as a DiffGram, which is a format used to identify current and original version of data elements.

  • XmlWriteMode.IgnoreSchema  Writes just the XML data. If the file contains no data, nothing is written.

  • XmlWriteMode.WriteSchema  Writes the XML data and the schema.



Part III: Programming Windows Forms