Write Dataset into XML,XMLSchema, Displaying in Gridview

In my previous article I wrote about how to read XML file and display it on Gridview.

In this article you find the way how to save the content in XML file from the user input with XML schema.

Here I use the XML schema to save structure of XML file.

Before proceeding you need to creat XML file and schema if not available.
For this I used the File streams to find existence of the files.


If System.IO.File.Exists(Server.MapPath("EmployeeSchema.xsd")) = False Or System.IO.File.Exists(Server.MapPath("Employees.xml")) = False Then Dim ds1 As New System.Data.DataSet Dim table As New DataTable, table1 As New DataTable Dim vcol(0) As DataColumn Try table1.TableName = "employees_details" table.TableName = "employee_info" table.Columns.Add("id", GetType(System.Int32)) table.Columns.Add("name", GetType(System.String)) table.Columns.Add("salary", GetType(System.String)) table1.Columns.Add("id", GetType(System.Int32)) table1.Columns.Add("name", GetType(System.String)) table1.Columns.Add("salary", GetType(System.String)) ds1.Tables.Add(table) ds1.Tables.Add(table1) ds1.WriteXmlSchema(Server.MapPath("EmployeeSchema.xsd")) ds1.WriteXml(Server.MapPath("Employees.xml")) Catch ex As Exception Finally table = Nothing table1 = Nothing ds1.Dispose() ds1 = Nothing End Try End If ds.ReadXmlSchema(Server.MapPath("EmployeeSchema.xsd")) ds.ReadXml(Server.MapPath("Employees.xml")) gv_XML.DataSource = ds.Tables("employee_info").DefaultView gv_XML.DataBind()

In this code I created the XML file if those are not available with schema.




ds.ReadXmlSchema(Server.MapPath("EmployeeSchema.xsd")) ds.ReadXml(Server.MapPath("Employees.xml"))

After that I saved these XML file and XML schema to the dataset object.

In XML file we are storing the all employees’ information.

XML file contains the three child elements. Those are Employee Id, name, Salary of the Employee.

For front end we have three textboxes and one Button controls.

After user entering the data we need to save to XML file by using schema and we are displaying using gridview


Dim row1 As DataRow ds.ReadXmlSchema(Server.MapPath("EmployeeSchema.xsd")) ds.ReadXml(Server.MapPath("Employees.xml")) row1 = ds.Tables(0).NewRow row1.Item(0) = id.Text row1.Item(1) = name.Text row1.Item(2) = sal.Text ds.Tables(0).Rows.Add(row1) ds.WriteXml(Server.MapPath("Employees.xml")) gv_XML.DataSource = ds.Tables("employee_info").DefaultView gv_XML.DataBind()

To append data with existing data, we created new row for dataset table.

We assign the id, name and salary values to this row by specifying the column names or column indexes.

Even you can save database table to the XML file with same structure.



Download source code here