DataSets and XML – A Perfect Combination

Working with DataSet and XML

This section discusses how we can perform the CRUD operations using DataSet and XML as the database to store the data.

Storing a DataSet instance to a XML File

The code sample below demonstrates how we can store data from a DataSet object directly to a disk file in XML format. The resultant XML document has been named as employee.xml
string connectionString = …; //Some connection string
SqlConnection sqlConnection =
new SqlConnection(connectionString);
SqlDataAdapter sqlDataAdapter =
new SqlDataAdapter(
“select name,id,joindate from employee”, sqlConnection);
sqlConnection.Open();
DataSet dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet);
dataSet.WriteXmlSchema(Server.MapPath(“employee.xml”));
dataSet.WriteXml(Server.MapPath(“employee.xml”));
 
 

Read Data from a XML file using a DataSet

 
The code that follows illustrates how we can search data from a XML document using a DataSet. The name of the method used is SearchData that returns a signed integer value of -1 if the record being searched (employee ID in our case is the key on which the search operation is being performed) is not found.
private int SearchData(int empID)
{
string filePath = …; //Some path indicating where the xml file // is stored
DataSet dataSetEmployee = GetEmployeeDataSet(); //Retrieve the // employee DataSet instance
DataTable dataTableEmployee = dataSetEmployee.Products.Tables[0];
DataView dataViewEmployee = new DataView();
dataViewEmployee = dataTableEmployee.DefaultView;
dataViewEmployee.Sort = “Emp_ID”;
int rowIndex = dataViewEmployee.Find(“empID”);
return rowIndex;
}

Note that once the SearchData method returns the value of the row index (a value that is not equal to -1), an employee DataSet instance can be easily populated with the data representing the particular employee identified by the unique employee ID.

Add data to a XML file using a DataSet

The code sample below illustrates how we can append data to the xml file created above using a DataSet instance.
DataSet dataSetEmployee = GetEmployeeDataSet(); // The
// GetEmployeeDataSet method populates a DataSet object with
// employee data and schema information and returns the instance
DataRow employeeRecord = dataSetEmployee.Tables[0].NewRow();
employeeRecord[0] = 1;
employeeRecord[1] = “Joydip Kanjilal”;
dataSetEmployee.Tables[0].Rows.Add(employeeRecord);
string filePath = …; //Some path where the file is stored
dataSetEmployee.WriteXml(filePath,XmlWriteMode.WriteSchema);

Continues…

Leave a comment

Your email address will not be published.