Output DataSet to Xml : Xml DataSet « XML « C# / CSharp Tutorial






using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

  class Program
  {
    static void Main(string[] args)
    {
      DataSet carsInventoryDS = new DataSet("Car");

      carsInventoryDS.ExtendedProperties["TimeStamp"] = DateTime.Now;
      carsInventoryDS.ExtendedProperties["DataSetID"] = Guid.NewGuid();
      carsInventoryDS.ExtendedProperties["Company"] = "Training";

      DataColumn carIDColumn = new DataColumn("CarID", typeof(int));
      carIDColumn.Caption = "Car ID";
      carIDColumn.ReadOnly = true;
      carIDColumn.AllowDBNull = false;
      carIDColumn.Unique = true;
      carIDColumn.AutoIncrement = true;
      carIDColumn.AutoIncrementSeed = 0;
      carIDColumn.AutoIncrementStep = 1;

      DataColumn carMakeColumn = new DataColumn("Make", typeof(string));
      DataColumn carColorColumn = new DataColumn("Color", typeof(string));
      DataColumn carPetNameColumn = new DataColumn("PetName", typeof(string));
      carPetNameColumn.Caption = "Pet Name";

      DataTable inventoryTable = new DataTable("Inventory");
      inventoryTable.Columns.AddRange(new DataColumn[] { carIDColumn, carMakeColumn, carColorColumn, carPetNameColumn });

      DataRow carRow = inventoryTable.NewRow();
      carRow["Make"] = "BMW";
      carRow["Color"] = "Black";
      carRow["PetName"] = "Hamlet";
      inventoryTable.Rows.Add(carRow);

      carRow = inventoryTable.NewRow();
      carRow[1] = "A";
      carRow[2] = "B";
      carRow[3] = "C";
      inventoryTable.Rows.Add(carRow);

      inventoryTable.PrimaryKey = new DataColumn[] { inventoryTable.Columns[0] };
      carsInventoryDS.Tables.Add(inventoryTable);
      
      // Save this DataSet as XML.
      carsInventoryDS.WriteXml("carsDataSet.xml");
      carsInventoryDS.WriteXmlSchema("carsDataSet.xsd");

      // Clear out DataSet.
      carsInventoryDS.Clear();

      // Load DataSet from XML file.
      carsInventoryDS.ReadXml("carsDataSet.xml");
      
    }
  }








30.28.Xml DataSet
30.28.1.Fill DataSet with the data from XML
30.28.2.Load XML to DataSet
30.28.3.Save data in a DataSet to xml document
30.28.4.Create Data with DataSet and DataRow and save to xml
30.28.5.Output DataSet to Xml
30.28.6.Reading XML with DataSet