您的位置:首页 > 其它

写了一个操作XML文件的类

2007-06-05 19:24 134 查看
一个操作XML文件的类。。部份功能在完善中~~~~

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
/*
* 作者 By感觉De味道;
* 版板 SghComm1.0
* 联系方式:ZhouFLeru@hotmail.com
*/
namespace TextCom
{
class SettingXml
{
private static System.Xml.XmlDocument xDoc = null;//加载配置文件用到;
//生成配置文件;
public static void NewSeeting()
{
string[] addkey ={ "Port", "BaudRate", "DataBits", "Parity", "StopBits" };
string[] addvalue ={ "1", "38400", "8", "0", "1" };
XmlDocument xmldoc;//XMl文档
XmlNode xmlnode;//XMl 中的节点
XmlElement xmlelem; //XML中元素
xmldoc = new XmlDocument();
XmlDeclaration xmlDec = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
//加入XML的声明段落
xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
//加入一个根元素
xmlelem = xmldoc.CreateElement("", "configuration", "");
xmldoc.AppendChild(xmlelem);
//加入另外一个元素
for (int i = 0; i < 5; i++)
{
XmlNode root = xmldoc.SelectSingleNode("configuration");//查找<configuration>
XmlElement xe1 = xmldoc.CreateElement("add");//创建一个<add>节点
xe1.SetAttribute("key", addkey[i] + "");
xe1.SetAttribute("value", addvalue[i] + "");
root.AppendChild(xe1);//添加到<configuration>节点中
}
//保存创建好的XML文档
xmldoc.Save("setting.config");
}
//Load配置文件;
public static string LoadSettingXml(string Appkey)
{
string path = "";
XmlNode LNode;
XmlElement LElem;

try {
path = "setting.config";

if (xDoc==null)
{
xDoc=new System.Xml.XmlDocument();
xDoc.Load(path);
}
}catch{throw new Exception("未发现配置文件!");}
try{

LNode = xDoc.SelectSingleNode("//configuration");
LElem = (XmlElement)LNode.SelectSingleNode("//add[@key='" + Appkey + "']");
if (LElem != null)
return LElem.GetAttribute("value");
else
return "";
}
catch
{
throw new Exception("Load配置文件错误!");
}
}
}
}
-----------------------------------------------------

成生如下结构:

<?xml version="1.0"?>
<configuration>
<add key="Port" value="1" />
<add key="BaudRate" value="38400" />
<add key="DataBits" value="8" />
<add key="Parity" value="0" />
<add key="StopBits" value="1" />
</configuration>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: