65.9K
CodeProject is changing. Read more.
Home

Using .xml files to replace small databases

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.06/5 (31 votes)

Sep 3, 2003

1 min read

viewsIcon

193004

downloadIcon

1629

Let an XML file become your local small database.

Sample Image

Introduction

Many software and projects have many files to save data, like .ini, .cfg, .config... And they use any small database hourly, like .mdb. Now, using XML files can replace these files to save any data, under the .NET framework. There are 4 steps that let us complete this mission :p.

Step 1: Building an XML file.

The XML file's formatting must be familiar to you. Like this:

xmlfile

If you open this XML file in VS.NET, you can see button "Data" in the IDE's left bottom. Click the button, you can see some tables from this XML file. Like this:

Sample screenshot

Step 2: Using a DataSet to read XML file.

Create a WinForm project. Add an OpenFileDialog into the main form. We will use it to open the XML file. Like this:

if(openFileDialog1.ShowDialog()==DialogResult.OK) 
{ 
  DataSet ds=new DataSet(); 
  ds.read(openFileDialog1.FileName); 
}

Step 3: Control the DataSet.

In a DataSet instance, we can do some operations like select, add, delete, and update... This is a sample method to search some data:

public DataRow[] searchForm(string tables,string expression) 
{ 
  //ds is a DataSet instance. 
  DataTable dt=ds.Tables[tables]; 
  DataRow[] drs=dt.Select(expression); 
  return drs; 
}

And you can add other methods easily. Like these methods:

//delete some rows from a table.
public bool deleteRows(string tables,string expression)
{
  bool result=false;
  DataTable dt=ds.Tables[tables];
  DataRow[] drs=dt.Select(expression);
  if(drs.Length>0)
  {
    for(int i=0;i<drs.Length;i++) <DRS[].LENGTH;I++)<>drs[i].Delete();
    ds.WriteXml(fileName);
    result=true;
  }
  else
  {
    result=false;
  }
  return result;
}

Step 4: Using DataSet to save data.

One statement can finish the work. Like this:

//fileName is a xml file's full name. 
if(fileName!="") 
ds.WriteXml(fileName);

Now see, the XML file can save data and we can use DataSet to operate on the data :).