我這里用Winform和WebForm兩種為例說明怎樣操作xml文檔來作為配置文件進行讀取操作。
1.新建一個類,命名為“SystemConfig.cs”。代碼例如以下:
<span style="font-family:Microsoft YaHei;font-size:14px;">using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; namespace ConfigMgrTest { public class SystemConfig { #region"基本操作函數" /// <summary> /// 得到程序工作文件夾 /// </summary> /// <returns></returns> private static string GetWorkDirectory() { try { return Path.GetDirectoryName(typeof(SystemConfig).Assembly.Location); } catch { return System.Windows.Forms.Application.StartupPath; } } /// <summary> /// 推斷字符串是否為空串 /// </summary> /// <param name="szString">目標字符串</param> /// <returns>true:為空串;false:非空串</returns> private static bool IsEmptyString(string szString) { if (szString == null) return true; if (szString.Trim() == string.Empty) return true; return false; } /// <summary> /// 創建一個制定根節點名的XML文件 /// </summary> /// <param name="szFileName">XML文件</param> /// <param name="szRootName">根節點名</param> /// <returns>bool</returns> private static bool CreateXmlFile(string szFileName, string szRootName) { if (szFileName == null || szFileName.Trim() == "") return false; if (szRootName == null || szRootName.Trim() == "") return false; XmlDocument clsXmlDoc = new XmlDocument(); clsXmlDoc.AppendChild(clsXmlDoc.CreateXmlDeclaration("1.0", "GBK", null)); clsXmlDoc.AppendChild(clsXmlDoc.CreateNode(XmlNodeType.Element, szRootName, "")); try { clsXmlDoc.Save(szFileName); return true; } catch { return false; } } /// <summary> /// 從XML文件獲取相應的XML文檔對象 /// </summary> /// <param name="szXmlFile">XML文件</param> /// <returns>XML文檔對象</returns> private static XmlDocument GetXmlDocument(string szXmlFile) { if (IsEmptyString(szXmlFile)) return null; if (!File.Exists(szXmlFile)) return null; XmlDocument clsXmlDoc = new XmlDocument(); try { clsXmlDoc.Load(szXmlFile); } catch { return null; } return clsXmlDoc; } /// <summary> /// 將XML文檔對象保存為XML文件 /// </summary> /// <param name="clsXmlDoc">XML文檔對象</param> /// <param name="szXmlFile">XML文件</param> /// <returns>bool:保存結果</returns> private static bool SaveXmlDocument(XmlDocument clsXmlDoc, string szXmlFile) { if (clsXmlDoc == null) return false; if (IsEmptyString(szXmlFile)) return false; try { if (File.Exists(szXmlFile)) File.Delete(szXmlFile); } catch { return false; } try { clsXmlDoc.Save(szXmlFile); } catch { return false; } return true; } /// <summary> /// 獲取XPath指向的單一XML節點 /// </summary> /// <param name="clsRootNode">XPath所在的根節點</param> /// <param name="szXPath">XPath表達式</param> /// <returns>XmlNode</returns> private static XmlNode SelectXmlNode(XmlNode clsRootNode, string szXPath) { if (clsRootNode == null || IsEmptyString(szXPath)) return null; try { return clsRootNode.SelectSingleNode(szXPath); } catch { return null; } } /// <summary> /// 獲取XPath指向的XML節點集 /// </summary> /// <param name="clsRootNode">XPath所在的根節點</param> /// <param name="szXPath">XPath表達式</param> /// <returns>XmlNodeList</returns> private static XmlNodeList SelectXmlNodes(XmlNode clsRootNode, string szXPath) { if (clsRootNode == null || IsEmptyString(szXPath)) return null; try { return clsRootNode.SelectNodes(szXPath); } catch { return null; } } /// <summary> /// 創建一個XmlNode並加入到文檔 /// </summary> /// <param name="clsParentNode">父節點</param> /// <param name="szNodeName">結點名稱</param> /// <returns>XmlNode</returns> private static XmlNode CreateXmlNode(XmlNode clsParentNode, string szNodeName) { try { XmlDocument clsXmlDoc = null; if (clsParentNode.GetType() != typeof(XmlDocument)) clsXmlDoc = clsParentNode.OwnerDocument; else clsXmlDoc = clsParentNode as XmlDocument; XmlNode clsXmlNode = clsXmlDoc.CreateNode(XmlNodeType.Element, szNodeName, string.Empty); if (clsParentNode.GetType() == typeof(XmlDocument)) { clsXmlDoc.LastChild.AppendChild(clsXmlNode); } else { clsParentNode.AppendChild(clsXmlNode); } return clsXmlNode; } catch { return null; } } /// <summary> /// 設置指定節點中指定屬性的值 /// </summary> /// <param name="parentNode">XML節點</param> /// <param name="szAttrName">屬性名</param> /// <param name="szAttrValue">屬性值</param> /// <returns>bool</returns> private static bool SetXmlAttr(XmlNode clsXmlNode, string szAttrName, string szAttrValue) { if (clsXmlNode == null) return false; if (IsEmptyString(szAttrName)) return false; if (IsEmptyString(szAttrValue)) szAttrValue = string.Empty; XmlAttribute clsAttrNode = clsXmlNode.Attributes.GetNamedItem(szAttrName) as XmlAttribute; if (clsAttrNode == null) { XmlDocument clsXmlDoc = clsXmlNode.OwnerDocument; if (clsXmlDoc == null) return false; clsAttrNode = clsXmlDoc.CreateAttribute(szAttrName); clsXmlNode.Attributes.Append(clsAttrNode); } clsAttrNode.Value = szAttrValue; return true; } #endregion #region"配置文件的讀取和寫入" private static string CONFIG_FILE = "SystemConfig.xml"; /// <summary> /// 讀取指定的配置文件里指定Key的值 /// </summary> /// <param name="szKeyName">讀取的Key名稱</param> /// <param name="szDefaultValue">指定的Key不存在時,返回的值</param> /// <returns>Key值</returns> public static int GetConfigData(string szKeyName, int nDefaultValue) { string szValue = GetConfigData(szKeyName, nDefaultValue.ToString()); try { return int.Parse(szValue); } catch { return nDefaultValue; } } /// <summary> /// 讀取指定的配置文件里指定Key的值 /// </summary> /// <param name="szKeyName">讀取的Key名稱</param> /// <param name="szDefaultValue">指定的Key不存在時,返回的值</param> /// <returns>Key值</returns> public static float GetConfigData(string szKeyName, float fDefaultValue) { string szValue = GetConfigData(szKeyName, fDefaultValue.ToString()); try { return float.Parse(szValue); } catch { return fDefaultValue; } } /// <summary> /// 讀取指定的配置文件里指定Key的值 /// </summary> /// <param name="szKeyName">讀取的Key名稱</param> /// <param name="szDefaultValue">指定的Key不存在時,返回的值</param> /// <returns>Key值</returns> public static bool GetConfigData(string szKeyName, bool bDefaultValue) { string szValue = GetConfigData(szKeyName, bDefaultValue.ToString()); try { return bool.Parse(szValue); } catch { return bDefaultValue; } } /// <summary> /// 讀取指定的配置文件里指定Key的值 /// </summary> /// <param name="szKeyName">讀取的Key名稱</param> /// <param name="szDefaultValue">指定的Key不存在時,返回的值</param> /// <returns>Key值</returns> public static string GetConfigData(string szKeyName, string szDefaultValue) { string szConfigFile = string.Format("{0}\\{1}", GetWorkDirectory(), CONFIG_FILE); if (!File.Exists(szConfigFile)) { return szDefaultValue; } XmlDocument clsXmlDoc = GetXmlDocument(szConfigFile); if (clsXmlDoc == null) return szDefaultValue; string szXPath = string.Format(".//key[@name='{0}']", szKeyName); XmlNode clsXmlNode = SelectXmlNode(clsXmlDoc, szXPath); if (clsXmlNode == null) { return szDefaultValue; } XmlNode clsValueAttr = clsXmlNode.Attributes.GetNamedItem("value"); if (clsValueAttr == null) return szDefaultValue; return clsValueAttr.Value; } /// <summary> /// 保存指定Key的值到指定的配置文件里 /// </summary> /// <param name="szKeyName">要被改動值的Key名稱</param> /// <param name="szValue">新改動的值</param> public static bool WriteConfigData(string szKeyName, string szValue) { string szConfigFile = string.Format("{0}\\{1}", GetWorkDirectory(), CONFIG_FILE); if (!File.Exists(szConfigFile)) { if (!CreateXmlFile(szConfigFile, "SystemConfig")) return false; } XmlDocument clsXmlDoc = GetXmlDocument(szConfigFile); string szXPath = string.Format(".//key[@name='{0}']", szKeyName); XmlNode clsXmlNode = SelectXmlNode(clsXmlDoc, szXPath); if (clsXmlNode == null) { clsXmlNode = CreateXmlNode(clsXmlDoc, "key"); } if (!SetXmlAttr(clsXmlNode, "name", szKeyName)) return false; if (!SetXmlAttr(clsXmlNode, "value", szValue)) return false; // return SaveXmlDocument(clsXmlDoc, szConfigFile); } #endregion } } </span>
PS:假設是Winform,則不用改動SystemConfig.cs的代碼,假設是WebForm的話則需改動后面的路徑和寫入與讀取的代碼。將我標紅框的刪除就可以,如圖:
2.WinForm的界面例如以下:
cs代碼例如以下:
<pre name="code" class="csharp"><span style="font-family:Microsoft YaHei;font-size:14px;">using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace ConfigMgrTest { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { //保存 SystemConfig.WriteConfigData("UserID", this.txtUserID.Text.Trim()); SystemConfig.WriteConfigData("Password", this.txtPassword.Text.Trim()); SystemConfig.WriteConfigData("Birthday",this.textBox3.Text.Trim()); this.txtUserID.Text = null; this.txtPassword.Text = null; this.textBox3.Text = null; MessageBox.Show("成功保存到配置文件" + Application.StartupPath + "SystemConfig.xml \n點擊讀取button進行讀取!"); } private void btnClose_Click(object sender, EventArgs e) { //讀取 this.txtUserID.Text = SystemConfig.GetConfigData("UserID", string.Empty); this.txtPassword.Text = SystemConfig.GetConfigData("Password", string.Empty); this.textBox3.Text = SystemConfig.GetConfigData("Birthday", string.Empty); } } }</span>
3.WebForm效果例如以下:
前台代碼例如以下:
<span style="font-family:Microsoft YaHei;font-size:14px;"><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Tc.Web.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="url1:"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <p> <asp:Label ID="Label2" runat="server" Text="url2:"></asp:Label> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </p> <asp:Button ID="Button1" runat="server" Text="寫入" onclick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="讀取" onclick="Button2_Click" /> </form> </div> </body> </html> </span>
后台代碼例如以下:
<span style="font-family:Microsoft YaHei;font-size:14px;">using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Tc.Web._Code; namespace Tc.Web { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button2_Click(object sender, EventArgs e) { //讀取 this.TextBox1.Text = SystemConfig.GetConfigData("url1", string.Empty); this.TextBox2.Text = SystemConfig.GetConfigData("url2", string.Empty); } protected void Button1_Click(object sender, EventArgs e) { //寫入 SystemConfig.WriteConfigData("url1", this.TextBox1.Text.Trim()); SystemConfig.WriteConfigData("url2", this.TextBox2.Text.Trim()); this.TextBox1.Text = null; this.TextBox2.Text = null; } } }</span>
終於xml文檔效果如圖:
PS:這里順便給大家推薦一款軟件,名字叫“ FirstObject XML Editor”:
FirstObject XML Editor是一個頗具特色的XML編輯器。該編輯器對中文的支持良好。能夠快速載入XML文檔,並生成可自己定義的樹視圖以顯示 XML 文檔的數據結構(很有特色。為其它 XML 編輯器所無)。能夠調用 MSXML 分析引擎驗證 XML 文檔的正確性和有效性。
其獨特的 FOAL 語言還能夠用於編程處理 XML 文檔,這也是一般的 XML 編輯器所無的。
FirstObject XML Editor除了支持一般的 XML 編輯功能之外,還具有生成 XML 節點相應的 XPath 定位表達式、獲取所選文字的 Unicode 代碼、對 XML 代碼進行自己主動縮進排版以便閱讀等特殊功能。推薦各位 XML 愛好者嘗試本編輯器。
並且,這是一個免費的軟件,你能夠一直使用它。如圖所看到的:
PS:“FirstObject XML Editor”及WinForm之xml讀取配置文件Demo下載地址:http://115.com/lb/5lbdzr1o4qf1
115網盤禮包碼:5lbdzr1o4qf1