c#讀取xml檔案設定檔Winform及WebForm-Demo詳解

來源:互聯網
上載者:User

標籤:c#

我這裡用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點擊讀取按鈕進行讀取!");        }        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


c#讀取xml檔案設定檔Winform及WebForm-Demo詳解

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.