我遇到了将表单数据保存回xml文件的问题,我最初从中导入了一些数据。
为简单起见,假设我有一个客户数据,名字和姓氏,我将其从文件导入datagridview。在这里,我有额外的表格文件放在我添加地址,电话号码和客户图片等详细信息。
一旦我添加了这些数据,我需要用xml中的这3个额外字段保存我的初始文件。如果需要,可以再次阅读。
我是新手并坚持如何做到这一点,请帮忙。感谢。
答案 0 :(得分:0)
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
您可以将新元素附加到XML DOM。 以下是更多信息:http://www.w3schools.com/dom/dom_nodes_add.asp
答案 1 :(得分:0)
由于您没有发布任何代码段,假设您没有任何结构,我已创建Employee
类作为Data Model
//Data Model
class Employee
{
string _firstName;
string _lastName;
string _address;
string _phoneNumber;
string _picturePath;
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public string PicturePath { get; set; }
}
private static void InitializeDataTableFromXML(ref DataTable dataTable)
{
// you can read your new details from Contorls's value from your Form, then form a Enumerable collection like List<Employee> employees, and create a DataTable as folllows
List<Employee> employees = new List<Employee>();
// form your collection
employees.Add(new Employee() { FirstName = "your First Name from XML File", LastName = "your Last Name from XML File or from Form Control", Address = "your new Address from Form Control or from Form Control", PhoneNumber = "your new Phone Number from Form Control", PicturePath = "your new Picture path from Form Control" });
.
.
,
employees.Add(new Employee() { FirstName = "your First Name from XML File", LastName = "your Last Name from XML File or from Form Control", Address = "your new Address from Form Control or from Form Control", PhoneNumber = "your new Phone Number from Form Control", PicturePath = "your new Picture path from Form Control" });
DataRow dataRow;
foreach (var employee in employees)
{
dataRow = dataTable.NewRow();
dataRow["FirstName"] = employee.FirstName;
dataRow["LastName"] = employee.LastName;
dataRow["Address"] = employee.Address;
dataRow["PhoneNumber"] = employee.PhoneNumber;
dataRow["PicturePath"] = employee.PicturePath;
dataTable.Rows.Add(dataRow);
}
}
private static void ReadOverriteXML(string xmlFilePath, DataTable dtNewXMLData)
{
using (XmlWriter writer = XmlWriter.Create(xmlFilePath))
{
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
foreach (DataRow row in dtNewXMLData.Rows)
{
writer.WriteStartElement("Employee");
writer.WriteElementString("FirstName", row["FirstName"].ToString());
writer.WriteElementString("LastName", row["LastName"].ToString());
writer.WriteElementString("Address", row["Address"].ToString());
writer.WriteElementString("PhoneNumber", row["PhoneNumber"].ToString());
writer.WriteElementString("PicturePath", row["PicturePath"].ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
// call to the methods
DataTable dtXML = GetDatTable();
InitializeDataTableFromXML(ref dtXML);
ReadOverriteXML("Employee.xml", dtXML);