Cấp bậc tác giả:

DOTNET

Thêm xóa sửa tài liệu xml trong C#

Được viết bởi webmaster ngày 01/03/2015 lúc 02:52 PM
Trong những bài viết trước chúng ta đã biết làm thế nào để đọc và tìm kiếm trên tài liệu XML
  • 0
  • 15060

Thêm xóa sửa tài liệu xml trong C#

Nhưng chúng ta chưa biết làm sao để thay đổi nội dung của chúng, trong thực tế việc sửa đổi nội dung và bổ sung các thông tin vào XML là khá cần thiết và quan trọng,cho nên chúng ta cần phải nắm vững các thao tác này,để hiểu rõ thêm vấnđề chúng ta sẽ xây dựng một ứng dụng minh họa như sau:
Các chức năng của ứng dụng này:
- Cho phép hiển thị thông tin nhân viên đầu tiên,tiếp theo hay cuối cùng qua việc thao tácvới các button
- Thêm một nhân viên
- Sửa đổi thông tin một nhân viên(lưu ý employeeID là một thuộc tính của tài liệu XMLnên ta không thể thay đổi được)
- Xóa một nhân viên hiện có
Cấu trúc tài liệu xml được sử dụng trong bài viết:

<?xml version=”1.0″ encoding=”utf-8″?>
<!– This is list of employees –>
<employees><br/>
<employee employeeid=”1″>
<firstname>DotNet</firstname>
<lastname>Group</lastname>
<homephone>0999999</homephone>
<notes><![CDATA[Nhom Cong nghe thong tin]]></notes>
</employee>
<employee employeeid=”2″>
<firstname>Microsoft</firstname>
<lastname>MVC</lastname>
<homephone>123456</homephone>
<notes><![CDATA[Nhom Cong nghe thong tin]]></notes>
</employee>
<employee employeeid=”3″>
<firstname>Microsoft</firstname>
<lastname>ADO.NET</lastname>
<homephone>0911111111</homephone>
<nodes><![CDATA[Nhom Cong nghe thong tin]]></nodes>
</employee>
</employees>


Khi chương trình chạy, các combobox, textbox và label sẻ được điền đầy đủ thông tin, các thông tin này lấy từ tập tin employees.xml

Chúng ta sử dụng hàm fillcontrols() để điên thông tin lấy từ tập tin xml lên form

private void fillcontrols()
{
XmlNode node = doc.DocumentElement.ChildNodes[CurrentNodeIndex];
comboBox1.Text = node.Attributes[“employeeid”].Value;
textBox1.Text = node.ChildNodes[0].InnerText;
textBox2.Text = node.ChildNodes[1].InnerText;
textBox3.Text = node.ChildNodes[2].InnerText;
textBox4.Text = node.ChildNodes[3].InnerText;
updatelabel();
}

Chúng ta thấy trong câu lệnh :

XmlNode node = doc.DocumentElement.ChildNodes[CurrentNodeIndex];
Có một biến CurrentNodeIndex để chỉ Index tức là thuộc tính employeeid của đối tượng đang được chọn để hiển thị, biến này được khai báo đầu chương trình với giá trị được gán bằng không.

Để thay đổi giá trị hiển thị trên form, chúng ta chỉ việc tăng hoặc giảm CurrentNodeIndex là được. Khi chúng ta click vào 1 trong 4 button dưới đây :

Button trái ngoài cùng (first): khi chúng ta click vào đó thì chỉ số CurrentNodeIndex sẻ có giá trị là 0 và một đối tượng sẻ được load tương ứng lên form.

Button tiếp theo(pre): Dùng để giảm chỉ số CurrentNodeIndex đi một

Button tiếp theo (next): Dùng để tăng chỉ số CurrentNodeIndex lên một

Button cuối cùng (last): Sẻ tăng chỉ số CurrentNodeIndex lên tối đa.

Vì first và last tương tự nhau nên chúng tôi chỉ trình bày ở đây phần first (phần last các bạn có thể tham khảo thêm ở code kèm theo):

private void button4_Click(object sender, EventArgs e)
{
CurrentNodeIndex = 0; // gan chi so CurrêntNodIndex = 0
fillcontrols(); // load lại form theo chi so moi
}

Tương tự cho next và pre. Chúng tôi chỉ trình bày với next

private void button6_Click(object sender, EventArgs e)
{
// neu chi so hien tai chua phai la toi da
if (CurrentNodeIndex < doc.DocumentElement.ChildNodes.Count – 1)
{
CurrentNodeIndex++; // tang chi so CurrentNodeIndex lên 1
fillcontrols(); // load lại form theo chi so moi
}
else
return;
}
Chúng ta cũng có thể Thêm, Xửa, Xóa bằng cách nhấn các button dưới đây:
  • Button Add: thêm một đối tượng mới
  • Button Apdate: Sửa lại thông tin đối tượng đang chọn
  • Button Delete: Xoá đối tượng đang chọn.
Đầu tiên tôi xin trình bày cách add một đối tượng mới :

private void button1_Click(object sender, EventArgs e)
{
// kiểm tra xem các thuoc tinh them đã đầy đủ hay chua
if (textBox1.Text == “” || textBox2.Text == “” || textBox3.Text == “” || textBox4.Text == “”)
{
MessageBox.Show(“Please enter all details about employee”);
return;
}
//khoi tao cac các Xmlelemment
XmlElement employee = doc.CreateElement(“employee”);
XmlElement firstname = doc.CreateElement(“firstname”);
XmlElement lastanme = doc.CreateElement(“lastname”);
XmlElement homephone = doc.CreateElement(“homephone”);
XmlElement notes = doc.CreateElement(“nodes”);
//khoi tao Attribute
XmlAttribute employeeid = doc.CreateAttribute(“employeeid”);
employeeid.Value = comboBox1.Text;
//khoi tao cac Xmltext
XmlText firstnametext = doc.CreateTextNode(textBox1.Text);
XmlText lastnametext = doc.CreateTextNode(textBox2.Text);
XmlText homephonetext = doc.CreateTextNode(textBox3.Text);
XmlCDataSection notestext = doc.CreateCDataSection(textBox4.Text);
//them vao cac noi dung
employee.Attributes.Append(employeeid);
employee.AppendChild(firstname);
employee.AppendChild(lastanme);
employee.AppendChild(homephone);
employee.AppendChild(notes);
//them cac text vao cho cac element
firstname.AppendChild(firstnametext);
lastanme.AppendChild(lastnametext);
homephone.AppendChild(homephonetext);
notes.AppendChild(notestext);
//them vao file XML
doc.DocumentElement.AppendChild(employee);
doc.Save(Application.StartupPath + “/employees.xml”);
updatelabel();
}

Tiếp theo là Update lại thông tin của đối tượng đang chọn:

private void button2_Click(object sender, EventArgs e)
{
// Cũng kiem tra xem day du thong tin hay chua
if (textBox1.Text == “” || textBox2.Text == “” || textBox3.Text == “” || textBox4.Text == “”)
{
MessageBox.Show(“Please enter all Details employee”);
return;
}

XmlNode node = doc.SelectSingleNode(“//employee[@employeeid=””+comboBox1.SelectedItem+””]”);
if (node != null)
{
node.ChildNodes[0].InnerText = textBox1.Text;
node.ChildNodes[1].InnerText = textBox2.Text;
node.ChildNodes[2].InnerText = textBox3.Text;
XmlCDataSection notes = doc.CreateCDataSection(textBox4.Text);
node.ChildNodes[3].ReplaceChild(notes, node.ChildNodes[3].ChildNodes[0]);
}
doc.Save(Application.StartupPath + “/employees.xml”);
}

Cuối cùng là xóa đối tượng được chọn:

private void button3_Click(object sender, EventArgs e)
{
XmlNode node = doc.SelectSingleNode(“//employee[@employeeid=”” + comboBox1.SelectedItem + “”]”);
if (node != null)
{
doc.DocumentElement.RemoveChild(node);
doc.Save(Application.StartupPath + “/employees.xml”);
}
updatelabel();
}

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML