使用数据集追加到现有 xml 文件中
本文关键字:xml 文件 数据集 追加 | 更新日期: 2023-09-27 18:34:48
我编写了这段代码,但每次运行它时都有一个问题......它覆盖了我的XML文件,并且没有添加任何新内容这是我的XML文件:
- <DATA>
- <Users>
<MonopolyID>User2</MonopolyID>
<Password>pass2</Password>
<FirstName>User2Name</FirstName>
<LastName>User2LastName</LastName>
</Users>
</DATA>
您可以看到用户 1 已被覆盖无论如何,这是我的代码:
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..");
}
}
你需要使用 'ds。Merge(dt(;',如下例所示:
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>
让我知道这是否有帮助。