Next


Adding XML Files to the Project

• Click on “Web Site” menu – “Add New Item”.
• Select “XML File” option and enter the file name.
• Click on “Add”.
• Then the xml file will be added to the project.

Demo on Reading XML Document

readxml Employees.xml

<?xml version="1.0" encoding="utf-8" ?>
<employees>
  <emp>
    <empid>101</empid>
    <empname>Ram</empname>
    <salary>8739</salary>
  </emp>
  <emp>
    <empid>102</empid>
    <empname>Sita</empname>
    <salary>6782</salary>
  </emp>
  <emp>
    <empid>103</empid>
    <empname>Laxman</empname>
    <salary>7832</salary>
  </emp>
</employees>

Default.aspx.cs

    protected void btnReadXMLData_Click(object sender, EventArgs e)
    {
            DataSet ds = new DataSet();
        ds.ReadXml(Request.PhysicalApplicationPath + "Employees.xml");
        DataTable dt = ds.Tables[0];
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

Demo on Writing XML Document

write XML


Default.aspx.cs

using System.Data.SqlClient;

    protected void btnWriteXMLData_Click(object sender, EventArgs e)
    {
        string cnstr = "data source=.;user id=sa;password=123;initial catalog=sample";
        SqlConnection cn = new SqlConnection(cnstr);
        string sqlstr = "select * from students";
        SqlDataAdapter adp = new SqlDataAdapter(sqlstr, cn);
        DataSet ds = new DataSet();
        cn.Open();
        adp.Fill(ds);
        ds.WriteXml(Request.PhysicalApplicationPath + "students.xml");
        cn.Close();
        lblMessage.Text = "Data Written to XML Document.";
    }