【发布时间】:2020-05-27 10:25:14
【问题描述】:
您好我正在尝试使用 XDocument 将数据 gridview 保存到 XML 文件,但问题是当我单击导出按钮时,数据 gridview 变得清晰并且导出的 XML 文件为空
这个按钮从多个文本框填充数据网格视图:
private void add_Click(object sender, EventArgs e)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = txtOne.Text;
dataGridView1.Rows[n].Cells[1].Value = txtTwo.Text;
dataGridView1.Rows[n].Cells[2].Value = txtThree.Text;
}
此按钮导出为 XML:
private void Export_Click(object sender, EventArgs e)
{
const string FILENAME = @"c:\temp\test.xml";
XDocument doc = new XDocument(
new XDeclaration("1.0", "ISO-8859-1", null),
new XElement("root",
dt.AsEnumerable().Select(row => new XElement("child", new object[]{
new XElement("one",row[0]),
new XElement("two",row[1]),
new XElement("three",row[2]),
}));
dataGridView1.DataSource = dt;
doc.Save(FILENAME);
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "File Name |*.xml";
saveFileDialog1.FilterIndex = 1;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
doc.Save(saveFileDialog1.FileName);
}
【问题讨论】:
-
请提供最小的、可重现的示例。 stackoverflow.com/help/minimal-reproducible-example
-
由于您的数据源是一个数据表,您可以在一条指令 dt.WriteXml(filename) 中将数据表写入 xml。不要用新数据填充 DGV,而是将新数据添加到数据表中。
标签: c# parsing xml-parsing