我正在尝试将datagridview中的每一行保存到现有的xml文件中,我知道如何将texbox保存到xml文件,但是我如何才能使这个数据网格视图行工作?
// Save values to XML profile
doc = new XmlDocument();
doc.Load(documentpath + @"\folder\" + cmb.SelectedItem + ".xml");
root = doc.DocumentElement;
root.GetElementsByTagName("Series")[0].InnerText = txtSeriesCP.Text;
root.GetElementsByTagName("Chassis")[0].InnerText = txtChassisCP.Text;
root.GetElementsByTagName("Car")[0].InnerText = txtCarCP.Text;
root.GetElementsByTagName("Owner")[0].InnerText = txtOwnerCP.Text;
root.GetElementsByTagName("Year")[0].InnerText = txtYearCP.Text;
root.GetElementsByTagName("VIN")[0].InnerText = txtVinCP.Text;
root.GetElementsByTagName("Type")[0].InnerText = txtTypeCP.Text;
root.GetElementsByTagName("Mileage")[0].InnerText = txtMileageCP.Text;
root.GetElementsByTagName("Line")[0].InnerText = txtLineCP.Text;
root.GetElementsByTagName("Package")[0].InnerText = txtPackageCP.Text;
root.GetElementsByTagName("Color")[0].InnerText = txtColorCP.Text;
// Save codings to XML profile
foreach (DataGridViewRow row in dataGridViewCP.Rows)
{
doc.CreateElement("Test");
}
doc.Save(documentpath + @"\folder\" + cmb.SelectedItem + ".xml");
我的xml看起来像这样
<?xml version="1.0" encoding="utf-8"?>
<carprofile>
<Carinfo>
<Series></Series>
<Chassis>F</Chassis>
<Car></Car>
<Type></Type>
<Year></Year>
<Owner></Owner>
<VIN></VIN>
<Mileage></Mileage>
<Line></Line>
<Package></Package>
<Color></Color>
</Carinfo>
<Codings>
<Applied-codings>
</Applied-codings>
</Codings>
</carprofile>
我想在标签内创建自己标签内的每一行,就像这样。
<Applied-codings>
<1>columnname1="test", columnname2="test2"</1>
<2>columnname1="test3", columnname2="test3"</2>
</Applied-codings>
答案 0 :(得分:0)
我认为你这样做很难。创建数据集要容易得多,并且可以将gridview绑定到数据集。您可以在一条指令中读取和写入数据集到xml。
DataSet carprofileDs = new DataSet("carprofile");
DataTable carInfoTable = new DataTable("Carinfo");
carprofileDs.Tables.Add(carInfoTable);
DataTable codingsTable = new DataTable("Codings");
carprofileDs.Tables.Add(codingsTable);
carInfoTable.Columns.Add("Series", typeof(string));
carInfoTable.Columns.Add("Chassis", typeof(string));
carInfoTable.Columns.Add("Car", typeof(string));
carInfoTable.Columns.Add("Type", typeof(string));
carInfoTable.Columns.Add("Year", typeof(string));
carInfoTable.Columns.Add("Owner", typeof(string));
carInfoTable.Columns.Add("Vin", typeof(string));
carInfoTable.Columns.Add("Milage", typeof(string));
carInfoTable.Columns.Add("Line", typeof(string));
carInfoTable.Columns.Add("Package", typeof(string));
carInfoTable.Columns.Add("Color", typeof(string));
codingsTable.Columns.Add("Applied-codings", typeof(string));
carprofileDs.WriteXml("filename", XmlWriteMode.WriteSchema);
carprofileDs = new DataSet();
carprofileDs.ReadXml("filename");