我想在xml文件中插入一条记录,应该如何做?
settings.xml文件内容如下:
<?xml version="1.0" encoding="gb2312"?>
<Settings>
<ConnectionString>测试</ConnectionString>
<BadCustomers>
<BadCustomer name="张三" />
<BadCustomer name="李四" />
<BadCustomer name="王五" />
<BadCustomer name="赵六" />
</BadCustomers>
</Settings>
我想在<BadCustomers>中加一条记录<BadCustomer name="张七" /> ,请问如何做?
我的代码是错误的,代码如下:
string xpath=System.IO.Path.Combine(Application.StartupPath, "settings.xml");;
DataSet ds=new DataSet();
FileStream fs=new FileStream(xpath,FileMode.Open);
ds.ReadXml(fs);
if(ds.Tables.Count==0)
{
fs.Close();
}
DataRow dr=ds.Tables[2].NewRow();//新建一行
dr["name"] = "张七";
ds.Tables[0].Rows.InsertAt(dr,0);//插入到第0行位置
MessageBox.Show("添加完成", "添加完成", MessageBoxButtons.OK, MessageBoxIcon.Information);