上一篇寫(xiě)到了讀取xml文件的方式,這一篇我們使用XmlDocument的方式將數據寫(xiě)入到xml文件;
為了增加用戶(hù)體驗,我們很多時(shí)候需要將頁(yè)面的一些配置信息保存下來(lái)。以方便下次使用的時(shí)候可以保持上次的使用狀態(tài)。由于控件的·屬性不盡相同,所以我們采用xml文件進(jìn)行一個(gè)結構化的保存。

界面信息如下,在點(diǎn)擊保存按鈕的時(shí)候我們需要將其需要的信息輸出到xml文件。


實(shí)現功能:
使用XmlDocument方式將界面信息保存到xml文件
開(kāi)發(fā)環(huán)境:
開(kāi)發(fā)工具:Visual Studio 2013
.NET Framework版本:4.5
實(shí)現代碼:
//保存界面控件信息Dictionary<string, ControlModel> dicView = new Dictionary<string, ControlModel>();private void btnSave_Click(object sender, EventArgs e){//獲取界面配置GetView(this);//要保存的xml路徑string xmlPath = Application.StartupPath + "\\viewConfig.xml";//使用XmlDocument創(chuàng )建XmlDocument xmlDoc = new XmlDocument();//指定xml文件基本條件和編碼格式//一般是第一行,如:<?xml version="1.0" encoding="gb2312"?>XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "gb2312", null);xmlDoc.AppendChild(xmlDec);//創(chuàng )建根節點(diǎn)XmlElement xmlelem = xmlDoc.CreateElement("", "viewConfig", "");foreach (var item in dicView){//根據控件名稱(chēng)創(chuàng )建節點(diǎn)XmlElement subNode = xmlDoc.CreateElement(item.Key);//根據需要保存的屬性創(chuàng )建節點(diǎn)System.Reflection.PropertyInfo[] pis = item.Value.GetType().GetProperties();foreach (var pi in pis){XmlElement subNodeProperty = xmlDoc.CreateElement(pi.Name);subNodeProperty.InnerText = Convert.ToString(pi.GetValue(item.Value));//設置屬性subNodeProperty.SetAttribute("desc", "描述信息");subNode.AppendChild(subNodeProperty);}xmlelem.AppendChild(subNode);}//將以上節點(diǎn)添加到XmlDocumentxmlDoc.AppendChild(xmlelem);//保存xml文件xmlDoc.Save(xmlPath);}//遞歸獲取需要保存的控件private void GetView(Control parent){foreach (Control c in parent.Controls){if (c.Controls.Count > 0){GetView(c);}else{if (c is TextBox){TextBox ctl = (TextBox)c;dicView.Add(ctl.Name, new ControlModel{Text = ctl.Text,Value = ctl.Text,Location = ctl.Location,Visible = ctl.Visible});}if (c is RadioButton){RadioButton ctl = (RadioButton)c;dicView.Add(ctl.Name, new ControlModel{Text = ctl.Text,Value = ctl.Checked.ToString(),Location = ctl.Location,Visible = ctl.Visible});}}}}//需要保存的控件信息模型private class ControlModel{public string Text { get; set; }public string Value { get; set; }public Point Location { get; set; }public bool Visible { get; set; }}
最后我們的輸出結果如下圖所示,根據上一篇所介紹的讀取方式。我們可以在頁(yè)面打開(kāi)的時(shí)候去讀取一下此文件,并將其信息設置到控件。

由簡(jiǎn)入繁,拿來(lái)即用
后續精彩,持續關(guān)注
聯(lián)系客服