博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#读取xml文件配置文件Winform及WebForm-Demo具体解释
阅读量:4335 次
发布时间:2019-06-07

本文共 12815 字,大约阅读时间需要 42 分钟。

我这里用WinformWebForm两种为例说明怎样操作xml文档来作为配置文件进行读取操作。

1.新建一个类,命名为“SystemConfig.cs”。代码例如以下:

using System;using System.Collections.Generic;using System.Text;using System.Xml;using System.IO;namespace ConfigMgrTest{    public class SystemConfig    {        #region"基本操作函数"        ///         /// 得到程序工作文件夹        ///         /// 
private static string GetWorkDirectory() { try { return Path.GetDirectoryName(typeof(SystemConfig).Assembly.Location); } catch { return System.Windows.Forms.Application.StartupPath; } } /// /// 推断字符串是否为空串 /// /// 目标字符串 ///
true:为空串;false:非空串
private static bool IsEmptyString(string szString) { if (szString == null) return true; if (szString.Trim() == string.Empty) return true; return false; } /// /// 创建一个制定根节点名的XML文件 /// /// XML文件 /// 根节点名 ///
bool
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; } } /// /// 从XML文件获取相应的XML文档对象 /// /// XML文件 ///
XML文档对象
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; } /// /// 将XML文档对象保存为XML文件 /// /// XML文档对象 /// XML文件 ///
bool:保存结果
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; } /// /// 获取XPath指向的单一XML节点 /// /// XPath所在的根节点 /// XPath表达式 ///
XmlNode
private static XmlNode SelectXmlNode(XmlNode clsRootNode, string szXPath) { if (clsRootNode == null || IsEmptyString(szXPath)) return null; try { return clsRootNode.SelectSingleNode(szXPath); } catch { return null; } } /// /// 获取XPath指向的XML节点集 /// /// XPath所在的根节点 /// XPath表达式 ///
XmlNodeList
private static XmlNodeList SelectXmlNodes(XmlNode clsRootNode, string szXPath) { if (clsRootNode == null || IsEmptyString(szXPath)) return null; try { return clsRootNode.SelectNodes(szXPath); } catch { return null; } } /// /// 创建一个XmlNode并加入到文档 /// /// 父节点 /// 结点名称 ///
XmlNode
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; } } /// /// 设置指定节点中指定属性的值 /// /// XML节点 /// 属性名 /// 属性值 ///
bool
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"; /// /// 读取指定的配置文件里指定Key的值 /// /// 读取的Key名称 /// 指定的Key不存在时,返回的值 ///
Key值
public static int GetConfigData(string szKeyName, int nDefaultValue) { string szValue = GetConfigData(szKeyName, nDefaultValue.ToString()); try { return int.Parse(szValue); } catch { return nDefaultValue; } } /// /// 读取指定的配置文件里指定Key的值 /// /// 读取的Key名称 /// 指定的Key不存在时,返回的值 ///
Key值
public static float GetConfigData(string szKeyName, float fDefaultValue) { string szValue = GetConfigData(szKeyName, fDefaultValue.ToString()); try { return float.Parse(szValue); } catch { return fDefaultValue; } } /// /// 读取指定的配置文件里指定Key的值 /// /// 读取的Key名称 /// 指定的Key不存在时,返回的值 ///
Key值
public static bool GetConfigData(string szKeyName, bool bDefaultValue) { string szValue = GetConfigData(szKeyName, bDefaultValue.ToString()); try { return bool.Parse(szValue); } catch { return bDefaultValue; } } /// /// 读取指定的配置文件里指定Key的值 /// /// 读取的Key名称 /// 指定的Key不存在时,返回的值 ///
Key值
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; } /// /// 保存指定Key的值到指定的配置文件里 /// /// 要被改动值的Key名称 /// 新改动的值 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 }}
PS:假设是Winform,则不用改动SystemConfig.cs的代码,假设是WebForm的话则需改动后面的路径和写入与读取的代码。将我标红框的删除就可以,如图:

2.WinForm的界面例如以下:

cs代码例如以下:

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);        }    }}
 
3.WebForm效果例如以下:

前台代码例如以下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Tc.Web.WebForm1" %>        

后台代码例如以下:

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;        }    }}
终于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下载地址:

         115网盘礼包码:5lbdzr1o4qf1

转载于:https://www.cnblogs.com/mengfanrong/p/5211720.html

你可能感兴趣的文章
Android学习笔记(十一)——从意图返回结果
查看>>
算法导论笔记(四)算法分析常用符号
查看>>
ultraedit激活
查看>>
总结(6)--- python基础知识点小结(细全)
查看>>
亿级曝光品牌视频的幕后设定
查看>>
ARPA
查看>>
JSP开发模式
查看>>
我的Android进阶之旅------&gt;Android嵌入图像InsetDrawable的使用方法
查看>>
Detours信息泄漏漏洞
查看>>
win32使用拖放文件
查看>>
Android 动态显示和隐藏软键盘
查看>>
raid5什么意思?怎样做raid5?raid5 几块硬盘?
查看>>
【转】how can i build fast
查看>>
null?对象?异常?到底应该如何返回错误信息
查看>>
django登录验证码操作
查看>>
(简单)华为Nova青春 WAS-AL00的USB调试模式在哪里开启的流程
查看>>
图论知识,博客
查看>>
[原创]一篇无关技术的小日记(仅作暂存)
查看>>
20145303刘俊谦 Exp7 网络欺诈技术防范
查看>>
原生和jQuery的ajax用法
查看>>