c#读取xml文件配置文件Winform及WebForm-Demo具体解释
我这里用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文档效果如图:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGlzZW55YW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
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具体解释的更多相关文章
- java 读取XML文件作为配置文件
首先,贴上自己的实例: XML文件:NewFile.xml(该文件与src目录同级) <?xml version="1.0" encoding="UTF-8&quo ...
- C#读取XML文件的基类实现
刚到新单位,学习他们的源代码,代码里读写系统配置文件的XML代码比较老套,直接写在一个系统配置类里,没有进行类的拆分,造成类很庞大,同时,操作XML的读写操作都是使用SetAttribute和node ...
- C#中经常使用的几种读取XML文件的方法
XML文件是一种经常使用的文件格式,比如WinForm里面的app.config以及Web程序中的web.config文件,还有很多重要的场所都有它的身影.Xml是Internet环境中跨平台的,依赖 ...
- DOM4J读取XML文件
最近在做DRP的项目,其中涉及到了读取配置文件,用到了DOM4J,由于是刚开始接触这种读取xml文件的技术,好奇心是难免的,于是在网上又找了一些资料,这里就结合找到的资料来谈一下读取xml文件的4中方 ...
- JAVA读取XML文件并解析获取元素、属性值、子元素信息
JAVA读取XML文件并解析获取元素.属性值.子元素信息 关键字 XML读取 InputStream DocumentBuilderFactory Element Node 前言 最 ...
- ASP.NET MVC 学习笔记-2.Razor语法 ASP.NET MVC 学习笔记-1.ASP.NET MVC 基础 反射的具体应用 策略模式的具体应用 责任链模式的具体应用 ServiceStack.Redis订阅发布服务的调用 C#读取XML文件的基类实现
ASP.NET MVC 学习笔记-2.Razor语法 1. 表达式 表达式必须跟在“@”符号之后, 2. 代码块 代码块必须位于“@{}”中,并且每行代码必须以“: ...
- Qt QtXml读取xml文件内容
Qt QtXml读取xml文件内容 xml文件内容 <?xml version="1.0" encoding="UTF-8"?> <YG_RT ...
- 利用SAX解析读取XML文件
xml 这是我的第一个BLOG,今天在看<J2EE应用开发详解>一书,书中讲到XML编程,于是就按照书中的步骤自己测试了起来,可是怎么测试都不成功,后来自己查看了一遍源码,发现在读 ...
- C#中常用的几种读取XML文件的方法
1.C#中常用的几种读取XML文件的方法:http://blog.csdn.net/tiemufeng1122/article/details/6723764/
随机推荐
- CSS自学笔记(15):CSS3多列布局
在CSS3中,也新增了一些关于文本布局的几个比较简单的属性.通过这些新增的属性,我们可以对文本进行简单的排版,就想报纸和杂志那样. 新增的部分属性,以及浏览器支持情况: 属性 浏览器支持 column ...
- JQuery DataTables Editor---只修改页面内容
近来在工作中需要对JQuery DataTables进行增,删,改的操作,在网上找了一些资料,感觉比较的好的就是(http://editor.datatables.net/)文章中所展示的操作方法(如 ...
- chrome浏览器debugger 调试,有意思。
JavaScript代码中加入一句debugger;来手工造成一个断点效果. 例子: ajax看看返回的数据内容,或者想知道js变量获取值是什么的时候. $.ajax({ type:"pos ...
- Final Exam Arrangement(ZOJ)
In Zhejiang University, there are N different courses labeled from 1 to N. Each course has its own t ...
- Jquery html页面处理基础
1.怎样获得浏览器的可视高度? var windHight = $(window).height(); //获得浏览器的可视高度 2.怎样获得滚动条相对于顶部的高度? var scrollHi ...
- poj3589---判断两个数有多接近
#include <stdio.h> #include <stdlib.h> int main() { ],s2[]; int a,b,i,j,n; scanf("% ...
- poj1423---求一个大数的位数方法,我猜网站上统计输入字符少于多少位的那个算法
法一:对一个数求它的对数,+1取整为其位数 问题转化为int (log10(N!)+1),对数性质log10(N!)=log10(N)+log10(N-1)+...+log10(1) /*用log10 ...
- Hoeffding连接到机器学习
统计学场景: 一个罐子中有红球和绿球,红球比例$v$未知,数量未知,如何得到红球比例?方法---随机抽样N个球,在其中红球占比为$u$ 由hoeffding可以知道:$P(|u-v|>\epsi ...
- ASP.NET 验证码 不同浏览器 不刷新问题
具体为什么不刷新是缓存机制不同,验证码图片的src或ImageUrl的获取是来自一个文件,由于连接地址没变所以不同内核浏览器有的会认为源没有变,解决办法就是在连接后面加上一个随机参数如可以用JS的Ma ...
- wcf系列学习5天速成——第五天 服务托管
今天是系列的终结篇,当然要分享一下wcf的托管方面的知识. wcf中托管服务一般有一下四种: Console寄宿: 利于开发调试,但不是生产环境中的最佳实践. winform寄 ...