従業員クラスから xml ファイルを作成しています。今、従業員の新しいレコードを既存の xml ファイルに追加したいと考えています。これどうやってするの?
ボタンをクリックすると、従業員の新しいレコードを XML で追加したいと考えています。
----- XML ファイル ----
<?xml version="1.0" encoding="utf-8"?>
<metadata>
<Employee ID="1" firstName="Usman" lastName="Shahzad" Salary="1000" />
<Employee ID="2" firstName="Mubasshir" lastName="Aashiq" Salary="1001" />
<Employee ID="3" firstName="Ishitiaq" lastName="Ch." Salary="1002" />
</metadata>
----- 分離コード -----
private void btnGet_Click(object sender, EventArgs e)
{
Employee[] employees = new Employee[3];
employees[0] = new Employee(1, "Usman", "Shahzad", 1000);
employees[1] = new Employee(2, "Mubasshir", "Aashiq", 1001);
employees[2] = new Employee(3, "Ishitiaq", "Ch.", 1002);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
string filename = @"Users\text1.xml";
Directory.CreateDirectory(Path.GetDirectoryName(filename));
using (XmlWriter xmlWriter = XmlWriter.Create(filename, settings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("metadata");
foreach (Employee a in employees)
{
xmlWriter.WriteStartElement("Employee");
xmlWriter.WriteAttributeString("ID", Convert.ToString(a.Id));
xmlWriter.WriteAttributeString("firstName", Convert.ToString(a.FirstName));
xmlWriter.WriteAttributeString("lastName", Convert.ToString(a.LastName));
xmlWriter.WriteAttributeString("Salary", Convert.ToString(a.Salary));
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
DialogResult dr = MessageBox.Show("XML file creation Done\nDo you want to load it into grid view?", "Testing", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (dr == DialogResult.OK)
{
ds.ReadXml(@"Users\text1.xml");
dataGridView1.DataSource = ds.Tables[0];
}
else
return;
}
class Employee
{
Int32 _id;
string _firstName;
string _lastName;
Int32 _salary;
public Employee(Int32 id, string firstName, string lastName, Int32 salary)
{
this._id = id;
this._firstName = firstName;
this._lastName = lastName;
this._salary = salary;
}
public Int32 Id { get { return _id; } }
public string FirstName { get { return _firstName; } }
public string LastName { get { return _lastName; } }
public Int32 Salary { get { return _salary; } }
}