using System.IO;
using System.Xml;
namespace LJLib.Tools.File
{
public class XmlConfig
{
///
/// 设置xml值
///
/// xml文件名
/// 段名
/// 值名
/// 取值
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("");
}
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);
}
///
/// 读取xml值
///
///
///
///
///
///
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("");
}
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");
}
}
}
}