123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- using System.IO;
- using System.Xml;
- namespace LJLib.Tools.File
- {
- public class XmlConfig
- {
- /// <summary>
- /// 设置xml值
- /// </summary>
- /// <param name="xmlPath">xml文件名</param>
- /// <param name="section">段名</param>
- /// <param name="keyname">值名</param>
- /// <param name="value">取值</param>
- public void SetXmlFileValue(string xmlPath, string section, string keyname, string value)
- {
- FileStream file = System.IO.File.Open(xmlPath, FileMode.OpenOrCreate);
- XmlDocument xDoc = new XmlDocument();
- try
- {
- xDoc.Load(file);
- }
- catch (System.Exception)
- {
- xDoc.LoadXml("<sections/>");
- }
- file.Close();
- XmlNode xRoot = xDoc.DocumentElement;
- XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("section[@name='" + section + "']");
- if (xSection == null)
- {
- xSection = xDoc.CreateElement("section");
- xSection.SetAttribute("name", section);
- xRoot.AppendChild(xSection);
- }
- XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']");
- if (xElem != null)
- {
- xElem.SetAttribute("value", value);
- }
- else
- {
- XmlElement xTmpElem = xDoc.CreateElement("add");
- xTmpElem.SetAttribute("key", keyname);
- xTmpElem.SetAttribute("value", value);
- xSection.AppendChild(xTmpElem);
- }
- xDoc.Save(xmlPath);
- }
- /// <summary>
- /// 读取xml值
- /// </summary>
- /// <param name="xmlPath"></param>
- /// <param name="section"></param>
- /// <param name="keyname"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- public string GetXmlFileValue(string xmlPath, string section, string keyname, string defaultValue)
- {
- if (!System.IO.File.Exists(xmlPath))
- {
- return defaultValue;
- }
- FileStream file = System.IO.File.OpenRead(xmlPath);
- XmlDocument xDoc = new XmlDocument();
- try
- {
- xDoc.Load(file);
- }
- catch (System.Exception)
- {
- xDoc.LoadXml("<sections/>");
- }
- file.Close();
- XmlNode xRoot = xDoc.DocumentElement;
- XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("section[@name='" + section + "']");
- if (xSection == null)
- {
- return defaultValue;
- }
- XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']");
- if (xElem == null)
- {
- return defaultValue;
- }
- else
- {
- return xElem.GetAttribute("value");
- }
- }
- }
- }
|