对于直接创建一个xml文件这个,直接略过。假设xml的初始内容如下面:
<?xml version="1.0"?> <Conf> </Conf>
哪,根节点是Conf。
添加节点
public static bool AddConfig(CommonConfig conf) { try { XmlDocument doc = new XmlDocument(); doc.Load(ConfigPath); XmlElement root = doc.DocumentElement; XmlElement body = doc.CreateElement("Config"); XmlElement CommonContent = doc.CreateElement("CommonContent"); CommonContent.InnerText = conf.CommonContent; XmlElement CommonPriority = doc.CreateElement("CommonPriority"); CommonPriority.InnerText = conf.CommonPriority.ToString(); body.AppendChild(CommonContent); body.AppendChild(CommonPriority); XmlAttribute Attr = doc.CreateAttribute("CommonName"); Attr.InnerText = conf.CommonName; body.Attributes.Append(Attr); root.AppendChild(body); doc.Save(ConfigPath); return true; } catch (Exception ex) { LogMsg.WriteLog("通用配置添加配置信息异常:" + ex.ToString()); return false; } } #endregion
编辑节点
public static bool ModifyConfig(CommonConfig conf) { try { XmlDocument doc = new XmlDocument(); doc.Load(ConfigPath); XmlElement root = doc.DocumentElement; XmlNode CommonContentNode = root.SelectSingleNode("/Conf/Config[@CommonName=‘" + conf.CommonName + "‘]/CommonContent"); CommonContentNode.InnerText = conf.CommonContent; //因为是用属性CommonName来确定节点的,所以将修改的操作放在最后,否则对于子节点将获取不到 XmlNode confNode = root.SelectSingleNode("/Conf/Config[@CommonName=‘" + conf.CommonName + "‘]"); confNode.Attributes["CommonName"].Value = conf.NewCommonName; doc.Save(ConfigPath); return true; } catch (Exception ex) { LogMsg.WriteLog("通用配置修改配置信息异常:" + ex.ToString()); return false; } }
获取所有节点
public static List<CommonConfig> GetAllConfig() { List<CommonConfig> ListConf = new List<CommonConfig>(); string CacheKey = "CommonConfig_Cache"; System.Web.Caching.Cache objCache = HttpRuntime.Cache; if (objCache[CacheKey] == null) { XmlDocument doc = new XmlDocument(); doc.Load(ConfigPath); XmlElement root = doc.DocumentElement; XmlNodeList nodeList=root.ChildNodes; foreach (XmlNode curNode in nodeList) { CommonConfig conf = new CommonConfig(); conf.CommonName = curNode.Attributes["CommonName"].Value; XmlNode contentNode=curNode.SelectSingleNode("CommonContent"); conf.CommonContent = contentNode.InnerText; XmlNode PriorityNode = curNode.SelectSingleNode("CommonPriority"); conf.CommonPriority = Convert.ToInt32(PriorityNode.InnerText); ListConf.Add(conf); } System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(ConfigPath); DataCache.SetCache(CacheKey, ListConf, dep); return ListConf; } else { return objCache[CacheKey] as List<CommonConfig>; } }
最终的结果是这样的:
<?xml version="1.0"?> <Conf> <Config CommonName="网站Logo"> <CommonContent>网站Logo</CommonContent> <CommonPriority>1</CommonPriority> </Config> </Conf>
上面需要使用XPath语法,我也记不住,所以放一个链接在这里,以后用到就去看看就行了。
可能以后还要添加一些对Xml的操作,未完待续……
时间: 2024-10-12 19:58:46