本案例將分析一個聯系人應用程序,在這裡將XML文檔充當數據庫來使用,所有的聯系人信息存儲在XML文檔中,同時,在程序中使用DOM對聯系人文檔進行查詢、編輯、更新等操作。具體來說本案例將實現以下功能:
1. 添加一個新的聯系人
2. 修改現有聯系人
3. 刪除現有聯系人
4. 按姓氏查詢聯系人
5. 按名字查詢聯系人
6. 將所有聯系人導出到另一個XML文件
7. 將聯系人從另一個XML文件導入
以下是程序運行效果圖:
應用程序主窗體:
添加聯系人窗體:
修改聯系人窗體:
以下是用於測試程序的XML文件:
contact.xml 將該文件保存在項目目錄下
<?xml version="1.0" encoding="gb2312"?> <ContactDetails> <Contact> <name> <first>Steven</first> <last>Perez</last> </name> <note>[email protected];system at http://www.details.net/token</note> </Contact> <Contact> <name> <first>Billoys</first> <last>Perez</last> </name> <note>[email protected];system at http://www.Billoys.com/Billoys.htm</note> </Contact> <Contact> <name> <first>劉</first> <last>羅鍋</last> </name> <note>古代人</note> </Contact> </ContactDetails>
contact2.xml 該文件用於實現導入聯系人功能,將該文件隨便保存在一個目錄下然後將保存路徑連同文件名拷貝到主窗體的“保存的路徑”文本框中再單擊“導入”按紐即可實現導入功能。
<?xml version="1.0" encoding="gb2312"?> <ContactDetails> <Contact> <name> <first>Steven</first> <last>Perez</last> </name> <note>[email protected];system at http://www.details.net/token</note> </Contact> <Contact> <name> <first>Billoys</first> <last>Perez</last> </name> <note>[email protected];system at http://www.Billoys.com/Billoys.htm</note> </Contact> <Contact> <name> <first>劉</first> <last>德華</last> </name> <note>香港著名藝人,工作勤懇同時不忘生活,出演電影100多部,演技已達登峰造極,刻畫人物栩栩如生</note> </Contact> <Contact> <name> <first>揚</first> <last>震</last> </name> <note>重案六組探員,為人膽大心細,沉著冷靜,富有人情味,經歷幾次案件後更加成熟,在成長中不斷磨練,是個真的漢子,正應驗那句話:成就靠真本事</note> </Contact> <Contact> <name> <first>季</first> <last>潔</last> </name> <note>重案六組探員,富有人情味,對揚震早已芳心默許,知道為什麼嗎?因為她天生就愛保護別人,當她看到揚震被別人用槍指著頭嚇的回不過神來時就對這個真實的男人產生了感覺,真可謂巾帼不讓須眉。 </Contact> </ContactDetails>
導出聯系人時在“保存的路徑”文本框中輸入一個文件路徑,程序將在該路徑下創建一個XML文件,如果該文件存在於該路徑上,程序將對該XML文件進行重寫。
為實現以上所述所有功能,我專門編寫了一個類來封裝實現代碼,該類代碼如下:
namespace ContactApplication { using System; using System.Xml; using System.Text; using System.Data; using System.Windows.Forms; using System.ComponentModel; using System.Collections; /// <summary> /// Contact 聯系人 /// </summary> public class Contact : IDisposable { private string xmlPath; private XmlDocument xmlDoc; private XmlNode selectNode; private string firstName; private string lastName; private string note; #region Contact 構造器 /// <summary> /// 默認構造器 /// </summary> public Contact() { this.xmlPath = "../../Contact.xml"; this.selectNode = null; this.xmlDoc = new XmlDocument(); this.xmlDoc.Load(this.xmlPath); this.firstName = string.Empty; this.lastName = string.Empty; this.note = string.Empty; } /// <summary> /// 使用姓氏,名字,個人信息構造一個聯系人對象 /// </summary> /// <param name="firstName">姓氏</param> /// <param name="lastName">名字</param> /// <param name="note">個人信息</param> public Contact(string firstName, string lastName, string note) { this.xmlPath = "../../Contact.xml"; this.selectNode = null; this.xmlDoc = new XmlDocument(); this.xmlDoc.Load(this.xmlPath); this.firstName = firstName; this.lastName = lastName; this.note = note; } #endregion #region Contact 資源釋放方法 /// <summary> /// 清理該對象所有正在使用的資源 /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// 釋放該對象的實例變量 /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (!disposing) return; if (this.xmlPath != null) this.xmlPath = null; if (this.xmlDoc != null) this.xmlDoc = null; if (this.selectNode != null) this.selectNode = null; if (this.firstName != null) this.firstName = null; if (this.lastName != null) this.lastName = null; if (this.note != null) this.note = null; } #endregion #region Contact 屬性 /// <summary> /// 姓氏 /// </summary> public string FirstName { get { return this.firstName; } set { this.firstName = value; } } /// <summary> /// 名字 /// </summary> public string LastName { get { return this.lastName; } set { this.lastName = value; } } /// <summary> /// 個人信息 /// </summary> public string Note { get { return this.note; } set { this.note = value; } } #endregion #region Contact 功能函數 /// <summary> /// 加載所有的聯系人姓名 /// </summary> /// <returns>聯系人姓名列表</returns> public ArrayList LoadContactName() { ArrayList nameList= new ArrayList(); XmlNodeList nameNodeList = xmlDoc.SelectNodes("//name"); foreach(XmlNode nameNode in nameNodeList) { XmlElement firstNameNode = (XmlElement)nameNode.FirstChild; XmlText firstNameText = (XmlText)firstNameNode.FirstChild; XmlElement lastNameNode = (XmlElement)nameNode.LastChild; XmlText lastNameText = (XmlText)lastNameNode.FirstChild; nameList.Add(lastNameText.Value + " " + firstNameText.Value); } return nameList; } /// <summary> /// 獲取note節點的文本值 /// </summary> /// <returns>note節點的文本值</returns> public string DisplayNote() { string note = string.Empty; XmlElement selectName = (XmlElement)xmlDoc.SelectSingleNode(string.Format("//name[first='{0}' and last='{1}']",this.firstName,this.lastName)); note = selectName.NextSibling.InnerText; return note; } /// <summary> /// 搜索聯系人 /// </summary> /// <remarks> /// 根據傳入的搜索類型(按姓或名)以及搜索值查詢符合條件的聯系人信息,並以對話框形式顯示 /// </remarks> /// <param name="searchType">搜索類型(first或last)</param> /// <param name="searchValue">搜索值</param> public void SearchContact(string searchType, string searchValue) { string contactInfo = string.Empty; int i = 0; XmlNodeList nameNodeList = xmlDoc.SelectNodes(string.Format("//name[{0}='{1}']",searchType,searchValue)); if(searchType == "first") { MessageBox.Show(string.Format("符合{0}姓氏的聯系人有{1}個",searchValue,nameNodeList.Count),"搜索聯系人",MessageBoxButtons.OK,MessageBoxIcon.Information); if (nameNodeList.Count == 0) return; foreach(XmlNode nameNode in nameNodeList) { i++; contactInfo = nameNode.LastChild.InnerText + " " + nameNode.FirstChild.InnerText; contactInfo = contactInfo + System.Environment.NewLine + "====================" + System.Environment.NewLine + nameNode.NextSibling.InnerText; MessageBox.Show(string.Format("第{0}個聯系人:{1}{2}{3}",i,System.Environment.NewLine,System.Environment.NewLine,contactInfo),"搜索聯系人",MessageBoxButtons.OK,MessageBoxIcon.Information); } } else if(searchType == "last") { MessageBox.Show(string.Format("符合{0}名字的聯系人有{1}個",searchValue,nameNodeList.Count),"搜索聯系人",MessageBoxButtons.OK,MessageBoxIcon.Information); if (nameNodeList.Count == 0) return; foreach(XmlNode nameNode in nameNodeList) { i++; contactInfo = nameNode.LastChild.InnerText + " " + nameNode.FirstChild.InnerText; contactInfo = contactInfo + System.Environment.NewLine + "====================" + System.Environment.NewLine + nameNode.NextSibling.InnerText; MessageBox.Show(string.Format("第{0}個聯系人:{1}{2}{3}",i,System.Environment.NewLine,System.Environment.NewLine,contactInfo),"搜索聯系人",MessageBoxButtons.OK,MessageBoxIcon.Information); } } else { MessageBox.Show("沒有發現與您的搜索條件匹配的項,請檢查您的操作是否正確!","搜索聯系人",MessageBoxButtons.OK,MessageBoxIcon.Information); } } /// <summary> /// 添加聯系人 /// </summary> public void AddContact() { XmlDocumentFragment xmlDocFrag = xmlDoc.CreateDocumentFragment(); XmlElement contactEle = xmlDoc.CreateElement("Contact"); XmlElement nameEle = xmlDoc.CreateElement("name"); XmlElement firstNameEle = xmlDoc.CreateElement("first"); firstNameEle.InnerText = this.firstName; nameEle.AppendChild(firstNameEle); XmlElement lastNameEle = xmlDoc.CreateElement("last"); lastNameEle.InnerText = this.lastName; nameEle.AppendChild(lastNameEle); XmlElement noteEle = xmlDoc.CreateElement("note"); noteEle.InnerText = this.note; contactEle.AppendChild(nameEle); contactEle.AppendChild(noteEle); xmlDocFrag.AppendChild(contactEle); XmlElement detailsEle = (XmlElement)xmlDoc.SelectSingleNode("/ContactDetails"); detailsEle.AppendChild(xmlDocFrag.FirstChild); xmlDoc.Save(this.xmlPath); } /// <summary> /// 修改聯系人 /// </summary> public void UpdateContact() { selectNode.FirstChild.InnerText = this.firstName; selectNode.LastChild.InnerText = this.lastName; selectNode.NextSibling.InnerText = this.note; xmlDoc.Save(this.xmlPath); } /// <summary> /// 刪除聯系人 /// </summary> public void DeleteContact() { XmlElement contactEle = (XmlElement)this.selectNode.ParentNode; XmlElement detailsEle = (XmlElement)contactEle.ParentNode; detailsEle.RemoveChild(contactEle); xmlDoc.Save(this.xmlPath); } /// <summary> /// 根據列表框中選中的聯系人在文檔中選擇一個對應的聯系人 /// </summary> public void SelectContact() { this.selectNode = xmlDoc.SelectSingleNode(string.Format("//name[first='{0}' and last='{1}']",this.firstName,this.lastName)); } /// <summary> /// 導出聯系人 /// </summary> /// <param name="filePath">要導出的路徑</param> /// <returns>是否成功導出</returns> public string ExportContacts(string filePath) { string isOk = "is not OK"; if (filePath != null) { XmlTextWriter xmlTxtWt = new XmlTextWriter(filePath,Encoding.UTF8); xmlDoc.Save(xmlTxtWt); xmlTxtWt.Close(); isOk = "is OK"; } return isOk; } /// <summary> /// 導入聯系人 /// </summary> /// <param name="filePath">要導入的路徑</param> public void ImportContacts(string filePath) { string impFirstName = string.Empty; string impLastName = string.Empty; XmlNode cNode; XmlDocument xmlDoc2 = new XmlDocument(); xmlDoc2.Load(filePath); XmlNodeList contactNodeList = xmlDoc2.SelectNodes("//Contact"); foreach(XmlNode contactNode in contactNodeList) { impFirstName = contactNode.FirstChild.FirstChild.ChildNodes[0].Value; impLastName = contactNode.FirstChild.LastChild.ChildNodes[0].Value; cNode = this.xmlDoc.SelectSingleNode(string.Format("//name[first='{0}' and last='{1}']",impFirstName,impLastName)); if (cNode == null) { XmlNode importNode = xmlDoc.ImportNode(contactNode,true); xmlDoc.SelectSingleNode("/ContactDetails").AppendChild(importNode); } } xmlDoc.Save(this.xmlPath); } #endregion } }