protected void btnRead_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Employee.xml"));//读取XML文件
//GridView控件配置数据源
gvEmployee.DataSource = ds;
gvEmployee.DataBind();
}
protected void btnWrite_Click(object sender, EventArgs e)
{
//创建DataTable
DataTable dt = new DataTable("Employee");
//创建DataColumn
DataColumn dcID = new DataColumn("ID", typeof(string));
DataColumn dcNAME = new DataColumn("NAME", typeof(string));
DataColumn dcAGE = new DataColumn("AGE", typeof(string));
DataColumn dcDEPT = new DataColumn("DEPT", typeof(string));
dt.Columns.AddRange(new DataColumn[] { dcID, dcNAME, dcAGE, dcDEPT });
//创建DataRow
DataRow dr = dt.NewRow();
dr["ID"] = "MR0004";
dr["NAME"] = "小李";
dr["AGE"] = "29";
dr["DEPT"] = "项目策划";
dt.Rows.Add(dr);
//创建一个DataSet
DataSet ds2 = new DataSet();
ds2.Tables.Add(dt);
//读取原有的XML数据
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Employee.xml"));
//合并两个DataSet
ds.Merge(ds2);
ds.WriteXml(Server.MapPath("Employee.xml"));
Page.ClientScript.RegisterStartupScript(GetType(), "", "alert('写入成功!');", true);
}
Employee.xml
<NewDataSet>
<Employee>
<ID>MR0001</ID>
<NAME>小王</NAME>
<AGE>27</AGE>
<DEPT>软件开发</DEPT>
</Employee>
<Employee>
<ID>MR0004</ID>
<NAME>小李</NAME>
<AGE>29</AGE>
<DEPT>项目策划</DEPT>
</Employee>
</NewDataSet>