[C#] Thao tác dữ liệu XML
Tác giả:
- Trần Hán Huy – tranhanhuy.wordpress.com
Đề bài
- Thao tác với XML (Select, insert, edit, delete)
1. Cấu trúc tập tin XML như sau:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <TuDien> <AnhViet> <TiengAnh>one</TiengAnh> <TiengViet>một</TiengViet> </AnhViet> <AnhViet> <TiengAnh>Two</TiengAnh> <TiengViet>hai</TiengViet> </AnhViet> </TuDien>
2. Class
AnhViet gồm 2 thành phần: TiengAnh, TiengViet
3. Read
public static List<AnhViet> ReadData(String pFilePath) { XmlDocument doc = new XmlDocument(); doc.Load(pFilePath); XmlNodeList nodelist = doc.SelectNodes("TuDien/AnhViet"); List<AnhViet> ds = new List<AnhViet>(); foreach (XmlNode q in nodelist) { AnhViet tAV = new AnhViet(q["TiengAnh"].InnerText, q["TiengViet"].InnerText); dssv.Add(tAV); } return dssv; }
4. Insert
public static bool InsertData(AnhViet pAV, String pFilePath) { try { XmlDocument doc = new XmlDocument(); doc.Load(pFilePath); XmlElement xAnhViet= doc.CreateElement("AnhViet"); XmlElement xEleTiengAnh= doc.CreateElement("TiengAnh"); XmlText xTiengAnh = doc.CreateTextNode(pAV.TiengAnh); xEleTiengAnh.AppendChild(xTiengAnh); xAnhViet.AppendChild(xEleTiengAnh); XmlElement xEleTiengViet = doc.CreateElement("TiengViet"); XmlText xTiengViet = doc.CreateTextNode(pAV.TiengViet); xEleTiengViet.AppendChild(xTiengViet); xAnhViet.AppendChild(xEleTiengViet); doc.DocumentElement.AppendChild(xAnhViet); doc.Save(pFilePath); return true; } catch { return false; } }
5. Update
public static bool SuaMotAnhViet(AnhViet pAVOld, AnhViet pAVNew, string pFilePath) { try { //load tập tin XML XmlDocument doc = new XmlDocument(); doc.Load(pFilePath); //chọn node XmlNode xNo = doc.SelectSingleNode("/TuDien/AnhViet[TiengAnh='" + pAVOld.TiengAnh + "']"); //sửa node xNo["TiengAnh"].InnerText = pAVNew.TiengAnh; xNo["TiengViet"].InnerText = pAVNew.TiengViet; doc.Save(pFilePath); return true; } catch { return false; } }
5. Delete
public static bool XoaMotAnhViet(AnhViet pAV, string pFilePath) { try { //load tập tin XML XmlDocument doc = new XmlDocument(); doc.Load(pFilePath); //chọn node XmlNode xNo = doc.SelectSingleNode("/TuDien/AnhViet[TiengAnh='" + pAV.TiengAnh + "']"); //xóa xNo.ParentNode.RemoveChild(xNo); //lưu tập tin XML doc.Save(pFilePath); return true; } catch { return false; } }
6. Thư viện sử dụng trong project
using System.Xml;