单例模式读取xml配置文件属性值要求:
程序启动后, 配置文件中的属性值要保持不变,才能起到作用;如果属性值在程序运行中一直在变化,那么就没有必要使用单例模式。
class SingleXMLConfigInfo
{
#region 定义一个获取本地XML配置的单例模式类
//1.私有的构造函数
private SingleXMLConfigInfo(){ }
//2.私有化、静态的getXMLConfigInfo的类对象,全局唯一。
private static SingleXMLConfigInfo XMLConfigInstance = null;
//3.定义一个静态且公用的方法用于统一调用该类中的方法
public static SingleXMLConfigInfo getXMLConfigInstance()
{
if(XMLConfigInstance == null) //判断不存在就创建。
{
XMLConfigInstance = new SingleXMLConfigInfo();
}
return XMLConfigInstance;
}
#endregion
/// <summary>
/// 一、加载本地SystemConfig.xml文件并查找根节点
/// </summary>
/// <param name="singleNode">传入要查找的节点</param>
/// <returns></returns>
public XmlNode getXMLConfigRoot(string singleNode)
{
//创建一个XmlDocument对象
XmlDocument xmlDoc = new XmlDocument();
//定义并获取程序运行时的本地路径
String xmlPath = System.Environment.CurrentDirectory;
//判断该路径下是否存在SystemConfig.xml文件
if(!File.Exists( xmlPath+"\\SystemConfig.xml"))
{
throw new Exception("This File isn't Exist!");
}
//加载SystemConfig.xml文件
xmlDoc.Load( xmlPath+"\\SystemConfig.xml");
//选中SystemConfig.xml文件中的根节点
XmlNode root = xmlDoc.SelectSingleNode("SystemConfigs");
//定义需要查找的节点
XmlNode NeedRoot = null;
//遍历根节点下的所有子节点
foreach(XmlNode childNode in root.ChildNodes)
{
//如果遍历得到的子节点与所需要查找的节点相同,则返回该节点
if(childNode.Name.Equals(singleNode))
{
NeedRoot = root.SelectSingleNode(singleNode);
}
}
return NeedRoot;
}
/// <summary>
/// 二、获取SystemConfig.xml文件中的预留电话/手机号码
/// </summary>
/// <param name="type">传入节点的属性名称</param>
/// <returns></returns>
public string getPersonalContactInfo(string type)
{
//得到所需的节点属性的父节点
XmlNode NeededRoot = getXMLConfigRoot("SelfPrePhone");
//定义变量用于暂时保存获取出来的节点属性的值
string NeedValue = "";
//如果所需杰节点属性的父节点不存在,则抛出错误信息
if (NeededRoot == null)
{
throw new Exception("读取配置节点SelfPrePhone文件错误");
}
//遍历所需节点的所有属性,并返回所查找的属性的值
foreach (XmlNode NeedTypeChildNode in NeededRoot.ChildNodes)
{
NeedValue = NeedTypeChildNode.Attributes[type].Value;
}
return NeedValue;
}
}
使用如下:
<SystemConfigs>
<AutoCloseSystemSet>
<CloseSystemTimeSet CloseTime="14:30:00"/>
</AutoCloseSystemSet>
<SelfPrePhone>
<PrePhone tel="0571-81234567" Phone="18765432173"></PrePhone>
</SelfPrePhone>
</SystemConfigs>
这段XML便是本地SystemConfig.xml文件中的内容信息
string test1 = SingleXMLConfigInfo.getXMLConfigInstance().getPersonalContactInfo("Phone");
string test3 = SingleXMLConfigInfo.getXMLConfigInstance().getPersonalContactInfo("tel");