假如一个xml文件如下:
<?xml version="1.0" encoding="utf-8"?> <!-- 注意: 除了手动编辑此文件以外,您还可以使用 Web 管理工具来 配置应用程序的设置。可以使用 Visual Studio 中的“网站”->“ASP.NET 配置” 选项。 设置和注释的完整列表在 machine.config.comments 中,该文件通常位于 \Windows\Microsoft.NET\Framework\v2.0.xxxxx\Config 中 --> <configuration> <appSettings> <add key="StartupFileWatch" value="True" /> <add key="MaxSize" value="2097152" /> <add key="MinSize" value="10" /> <add key="WatchDir" value="UpLoadFolder" /> <add key="IgnorePostfix" value=".html;.htm;.js" /> <add key="CsCommand" value="1" /> <add key="PeCommand" value="1" /> </appSettings> </configuration>
/// <summary> /// 是否启动实时监控 /// </summary> static public bool StartupFileWatch { get { string str = XML.GetConfig("StartupFileWatch",@"Config\TopWinCMS.FileWatcher.config"); return Convert.ToBoolean(str); } set { XML.SaveSetting("StartupFileWatch",value.ToString(),@"Config\TopWinCMS.FileWatcher.config"); } }
/// <summary> /// 读取 XML中指定节点值 /// </summary> /// <param name="strKeyName"></param> /// <returns></returns> public static string GetConfig(string strKeyName) { return GetConfig(strKeyName,"Web.config"); } /// <summary> /// 读取 XML中指定节点值 /// </summary> /// <param name="strKeyName">节点键名</param> /// <returns>指定节点键值</returns> public static string GetConfig(string strKeyName,string strWhich) { string configpath; try { configpath = string.Concat(System.Web.HttpRuntime.AppDomainAppPath,@"\",strWhich); } catch { configpath = System.Windows.Forms.Application.StartupPath; if (configpath.EndsWith(@"\bin")) { configpath = configpath.Substring(0,configpath.Length - 4); } configpath = string.Concat(configpath,strWhich); } using (XmlTextReader tr = new XmlTextReader(configpath)) { while (tr.Read()) { if (tr.NodeType == XmlNodeType.Element) { if (tr.Name == "add" && tr.GetAttribute("key") == strKeyName) { return tr.GetAttribute("value"); } } } } return null; }
/// <summary> /// 保存Web.config /// </summary> /// <param name="strKeyName">节点名</param> /// <param name="strKeyValue">要保存的值</param> /// <param name="strWhich">哪个配置文件</param> public static void SaveSetting(string strKeyName,string strKeyValue,string strWhich) { //创建XML文档实例 System.Xml.XmlDocument XMLWebSetting = new System.Xml.XmlDocument(); //打开XML文档 XMLWebSetting.Load(System.Web.HttpRuntime.AppDomainAppPath + "/" + strWhich); //查找节点所在位置 System.Xml.XmlNodeList XmlNodeList = XMLWebSetting.SelectSingleNode("//appSettings").ChildNodes; foreach (System.Xml.XmlNode xn in XmlNodeList) { if (xn.Attributes["key"].InnerText == strKeyName) { xn.Attributes["value"].InnerText = strKeyValue; XMLWebSetting.Save(System.Web.HttpContext.Current.Server.MapPath("~/" + strWhich + "")); break; } } }原文链接:https://www.f2er.com/xml/300259.html