我制作了这个代码,但它有一个问题,每次我运行它..覆盖我的xml文件,没有添加任何新的 这是我的xml文件:
- <DATA>
- <Users>
<MonopolyID>User2</MonopolyID>
<Password>pass2</Password>
<FirstName>User2Name</FirstName>
<LastName>User2LastName</LastName>
</Users>
</DATA>
你可以看到user1被覆盖了 无论如何这是我的代码:
public partial class SignUpPage : Form
{
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("MonopolyID", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("Password", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("FirstName", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("LastName", typeof(string));
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dt.Rows.Add(textBox3.Text, textBox4.Text, textBox1.Text, textBox2.Text);//here just putting the texts in the texts box for the first row
dt.TableName = "Users";
ds.Tables.Add(dt);
ds.DataSetName = "DATA";
ds.WriteXml(@"pathOfTheFile..");
}
}
答案 0 :(得分:1)
您需要使用&#39; ds.Merge(dt);&#39;如下例所示:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/xmldata.xml"));
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("MonopolyID", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("Password", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("FirstName", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("LastName", typeof(string));
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dt.Rows.Add("User3", "pass3", "User3Name", "User3LastName");
//dt.TableName = "Users";
ds.Tables.Add(dt);
//ds.DataSetName = "DATA";
ds.Merge(dt);
ds.WriteXml(Server.MapPath("~/xmldata.xml"));
}
到目前为止在xml文件下生成
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table1>
<MonopolyID>User1</MonopolyID>
<Password>pass1</Password>
<FirstName>User1Name</FirstName>
<LastName>User1LastName</LastName>
</Table1>
<Table2>
<MonopolyID>User2</MonopolyID>
<Password>pass2</Password>
<FirstName>User2Name</FirstName>
<LastName>User2LastName</LastName>
</Table2>
<Table3>
<MonopolyID>User3</MonopolyID>
<Password>pass3</Password>
<FirstName>User3Name</FirstName>
<LastName>User3LastName</LastName>
</Table3>
</NewDataSet>
如果有帮助,请告诉我。