写了一个操作XML文件的类
?一個操作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>
轉載于:https://www.cnblogs.com/zhoufleru/archive/2007/06/05/772579.html
總結
以上是生活随笔為你收集整理的写了一个操作XML文件的类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛顿法python代码_python 牛
- 下一篇: 沉没在阴天的慵懒中