Write for Us
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 stringSqlConnection 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"));
private int SearchData(int empID){string filePath = …; //Some path indicating where the xml file // is storedDataSet dataSetEmployee = GetEmployeeDataSet(); //Retrieve the // employee DataSet instanceDataTable 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.
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 instanceDataRow 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 storeddataSetEmployee.WriteXml(filePath,XmlWriteMode.WriteSchema);