如有不明白的地方欢迎加QQ群14670545探讨
看了一个CMS系统,当然大多都会有这样的功能。加入xml格式如下:
<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="iNethinkCMS"> <sys_configuration> <WebName><![CDATA[iNethinkCMS]]></WebName> <InstallDir><![CDATA[/]]></InstallDir> <UrlMode>1</UrlMode> <TemplateCache>false</TemplateCache> <WebPageCache>false</WebPageCache> <CacheKey><![CDATA[CacheKey]]></CacheKey> <CacheTime>1200</CacheTime> <TemplateDir><![CDATA[/template/BasicDemo/]]></TemplateDir> <RewriteChannelPrefix><![CDATA[channel]]></RewriteChannelPrefix> <RewriteSpecialPrefix><![CDATA[special]]></RewriteSpecialPrefix> <RewriteContentPrefix><![CDATA[content]]></RewriteContentPrefix> <RewriteGuestbookPrefix><![CDATA[guestbook]]></RewriteGuestbookPrefix> <RemoteImgDown>true</RemoteImgDown> <UpFileType><![CDATA[zip,rar,txt,doc,docx,xls,xlsx,jpg,jpeg,gif,png,bmp,swf,wmv,avi,wma,mp3,mid]]></UpFileType> <UpFileMaxSize>1024</UpFileMaxSize> <PageListNum>10</PageListNum> <ImageSeconds>5</ImageSeconds> </sys_configuration> </xs:schema>
model就不写了,类库:
using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace iNethinkCMS.Helper { public class XMLHelper { public XMLHelper() { } #region XML文档节点查询和读取 /// <summary> /// 选择匹配XPath表达式的第一个节点XmlNode. /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param> /// <returns>返回XmlNode</returns> public static XmlNode GetXmlNodeByXpath(string xmlFileName,string xpath) { XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); return xmlNode; } catch (Exception ex) { return null; throw ex; //这里可以定义你自己的异常处理 } } /// <summary> /// 选择匹配XPath表达式的节点列表XmlNodeList. /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param> /// <returns>返回XmlNodeList</returns> public static XmlNodeList GetXmlNodeListByXpath(string xmlFileName,string xpath) { XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath); return xmlNodeList; } catch (Exception ex) { return null; throw ex; //这里可以定义你自己的异常处理 } } /// <summary> /// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute. /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param> /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param> /// <returns>返回xmlAttributeName</returns> public static XmlAttribute GetXmlAttribute(string xmlFileName,string xpath,string xmlAttributeName) { string content = string.Empty; XmlDocument xmlDoc = new XmlDocument(); XmlAttribute xmlAttribute = null; try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); if (xmlNode != null) { if (xmlNode.Attributes.Count > 0) { xmlAttribute = xmlNode.Attributes[xmlAttributeName]; } } } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return xmlAttribute; } #endregion #region XML文档创建和节点或属性的添加、修改 /// <summary> /// 创建一个XML文档 /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="rootNodeName">XML文档根节点名称(须指定一个根节点名称)</param> /// <param name="version">XML文档版本号(必须为:"1.0")</param> /// <param name="encoding">XML文档编码方式</param> /// <param name="standalone">该值必须是"yes"或"no",如果为null,Save方法不在XML声明上写出独立属性</param> /// <returns>成功返回true,失败返回false</returns> public static bool CreateXmlDocument(string xmlFileName,string rootNodeName,string version,string encoding,string standalone) { bool isSuccess = false; try { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version,encoding,standalone); XmlNode root = xmlDoc.CreateElement(rootNodeName); xmlDoc.AppendChild(xmlDeclaration); xmlDoc.AppendChild(root); xmlDoc.Save(xmlFileName); isSuccess = true; } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return isSuccess; } /// <summary> /// 依据匹配XPath表达式的第一个节点来创建它的子节点(如果此节点已存在则追加一个新的同名节点 /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param> /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param> /// <param name="innerText">节点文本值</param> /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param> /// <param name="value">属性值</param> /// <returns>成功返回true,失败返回false</returns> public static bool CreateXmlNodeByXPath(string xmlFileName,string xmlNodeName,string innerText,string xmlAttributeName,string value) { bool isSuccess = false; XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); if (xmlNode != null) { //存不存在此节点都创建 XmlElement subElement = xmlDoc.CreateElement(xmlNodeName); subElement.InnerXml = innerText; //如果属性和值参数都不为空则在此新节点上新增属性 if (!string.IsNullOrEmpty(xmlAttributeName) && !string.IsNullOrEmpty(value)) { XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName); xmlAttribute.Value = value; subElement.Attributes.Append(xmlAttribute); } xmlNode.AppendChild(subElement); } xmlDoc.Save(xmlFileName); //保存到XML文档 isSuccess = true; } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return isSuccess; } /// <summary> /// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建) /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param> /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param> /// <param name="innerText">节点文本值</param> /// <returns>成功返回true,失败返回false</returns> public static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName,string innerText) { bool isSuccess = false; bool isExistsNode = false;//标识节点是否存在 XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); if (xmlNode != null) { //遍历xpath节点下的所有子节点 foreach (XmlNode node in xmlNode.ChildNodes) { if (node.Name.ToLower() == xmlNodeName.ToLower()) { //存在此节点则更新 node.InnerXml = innerText; isExistsNode = true; break; } } if (!isExistsNode) { //不存在此节点则创建 XmlElement subElement = xmlDoc.CreateElement(xmlNodeName); subElement.InnerXml = innerText; xmlNode.AppendChild(subElement); } } xmlDoc.Save(xmlFileName); //保存到XML文档 isSuccess = true; } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return isSuccess; } /// <summary> /// 依据匹配XPath表达式的第一个节点来创建或更新它的属性(如果属性存在则更新,不存在则创建) /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param> /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param> /// <param name="value">属性值</param> /// <returns>成功返回true,失败返回false</returns> public static bool CreateOrUpdateXmlAttributeByXPath(string xmlFileName,string value) { bool isSuccess = false; bool isExistsAttribute = false;//标识属性是否存在 XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); if (xmlNode != null) { //遍历xpath节点中的所有属性 foreach (XmlAttribute attribute in xmlNode.Attributes) { if (attribute.Name.ToLower() == xmlAttributeName.ToLower()) { //节点中存在此属性则更新 attribute.Value = value; isExistsAttribute = true; break; } } if (!isExistsAttribute) { //节点中不存在此属性则创建 XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName); xmlAttribute.Value = value; xmlNode.Attributes.Append(xmlAttribute); } } xmlDoc.Save(xmlFileName); //保存到XML文档 isSuccess = true; } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return isSuccess; } #endregion #region XML文档节点或属性的删除 /// <summary> /// 删除匹配XPath表达式的第一个节点(节点中的子元素同时会被删除) /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param> /// <returns>成功返回true,失败返回false</returns> public static bool DeleteXmlNodeByXPath(string xmlFileName,string xpath) { bool isSuccess = false; XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); if (xmlNode != null) { //删除节点 xmlNode.ParentNode.RemoveChild(xmlNode); } xmlDoc.Save(xmlFileName); //保存到XML文档 isSuccess = true; } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return isSuccess; } /// <summary> /// 删除匹配XPath表达式的第一个节点中的匹配参数xmlAttributeName的属性 /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param> /// <param name="xmlAttributeName">要删除的xmlAttributeName的属性名称</param> /// <returns>成功返回true,失败返回false</returns> public static bool DeleteXmlAttributeByXPath(string xmlFileName,string xmlAttributeName) { bool isSuccess = false; bool isExistsAttribute = false; XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); XmlAttribute xmlAttribute = null; if (xmlNode != null) { //遍历xpath节点中的所有属性 foreach (XmlAttribute attribute in xmlNode.Attributes) { if (attribute.Name.ToLower() == xmlAttributeName.ToLower()) { //节点中存在此属性 xmlAttribute = attribute; isExistsAttribute = true; break; } } if (isExistsAttribute) { //删除节点中的属性 xmlNode.Attributes.Remove(xmlAttribute); } } xmlDoc.Save(xmlFileName); //保存到XML文档 isSuccess = true; } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return isSuccess; } /// <summary> /// 删除匹配XPath表达式的第一个节点中的所有属性 /// </summary> /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param> /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param> /// <returns>成功返回true,失败返回false</returns> public static bool DeleteAllXmlAttributeByXPath(string xmlFileName,string xpath) { bool isSuccess = false; XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(xmlFileName); //加载XML文档 XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); if (xmlNode != null) { //遍历xpath节点中的所有属性 xmlNode.Attributes.RemoveAll(); } xmlDoc.Save(xmlFileName); //保存到XML文档 isSuccess = true; } catch (Exception ex) { throw ex; //这里可以定义你自己的异常处理 } return isSuccess; } #endregion } }
应用:
/// <summary> /// 更新 --- 系统配置 /// </summary> public bool Update_SysConfig(iNethinkCMS.Model.Model_Config model) { string strXmlFile = HttpContext.Current.Server.MapPath("~/config/sys.config"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"//sys_configuration","WebName","<![CDATA[" + model.WebName + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"InstallDir","<![CDATA[" + model.InstallDir + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"UrlMode",model.UrlMode.ToString()); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"TemplateCache",model.TemplateCache); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"WebPageCache",model.WebPageCache); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"TemplateDir","<![CDATA[" + model.TemplateDir + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"CacheTime",model.CacheTime); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"RewriteChannelPrefix","<![CDATA[" + model.RewriteChannelPrefix + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"RewriteSpecialPrefix","<![CDATA[" + model.RewriteSpecialPrefix + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"RewriteContentPrefix","<![CDATA[" + model.RewriteContentPrefix + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"RewriteGuestbookPrefix","<![CDATA[" + model.RewriteGuestbookPrefix + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"RemoteImgDown",model.RemoteImgDown); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"UpFileType","<![CDATA[" + model.UpFileType + "]]>"); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"UpFileMaxSize",model.UpFileMaxSize); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"PageListNum",model.PageListNum); XMLHelper.CreateOrUpdateXmlNodeByXPath(strXmlFile,"ImageSeconds",model.ImageSeconds); return true; }
/// <summary> /// 得到一个对象实体 --- 系统配置 /// </summary> public iNethinkCMS.Model.Model_Config GetModel_SysConfig() { string strXmlFile = HttpContext.Current.Server.MapPath("~/config/sys.config"); iNethinkCMS.Model.Model_Config model = new iNethinkCMS.Model.Model_Config(); model.WebName = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//WebName").InnerText.Trim(); model.InstallDir = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//InstallDir").InnerText.Trim(); model.UrlMode = int.Parse(XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//UrlMode").InnerText.Trim()); model.TemplateCache = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//TemplateCache").InnerText.Trim(); model.WebPageCache = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//WebPageCache").InnerText.Trim(); model.TemplateDir = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//TemplateDir").InnerText.Trim(); model.CacheKey = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//CacheKey").InnerText.Trim(); model.CacheTime = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//CacheTime").InnerText.Trim(); model.RewriteChannelPrefix = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//RewriteChannelPrefix").InnerText.Trim(); model.RewriteSpecialPrefix = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//RewriteSpecialPrefix").InnerText.Trim(); model.RewriteContentPrefix = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//RewriteContentPrefix").InnerText.Trim(); model.RewriteGuestbookPrefix = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//RewriteGuestbookPrefix").InnerText.Trim(); model.RemoteImgDown = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//RemoteImgDown").InnerText.Trim(); model.UpFileType = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//UpFileType").InnerText.Trim(); model.UpFileMaxSize = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//UpFileMaxSize").InnerText.Trim(); model.PageListNum = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//PageListNum").InnerText.Trim(); model.ImageSeconds = XMLHelper.GetXmlNodeByXpath(strXmlFile,"//sys_configuration//ImageSeconds").InnerText.Trim(); return model; }
不过真心觉得这样子很累,频发的操作,没有dtcms里面的反序列化思路好:
它的xml如下:
<?xml version="1.0"?> <siteconfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <webname>DTcms内容管理系统</webname> <webcompany>动力启航软件工作室</webcompany> <weburl>http://demo.dtcms.net</weburl> <webtel>13800138000</webtel> <webfax>-</webfax> <webmail>info@it134.cn</webmail> <webcrod>粤ICP备11064298号</webcrod> <webtitle>DTcms网站管理系统 - 动力启航_开源cms_NET开源_cms建站</webtitle> <webkeyword>动力启航,DTCMS系统,ASP.NET开源,开源CMS,网站管理系统,互联网开发</webkeyword> <webdescription>以ASP.NET(C#)+jQuery技术为中心,面向软件开发者、程序爱好者、网页设计师,服务于个人、企业的网站,同时也是一个专门结合AJAX技术开发友好界面、倍受欢迎用户体验的BS模式软件系统,打造自己的品牌。</webdescription> <webcopyright>版权所有 动力启航 © Copyright 2009 - 2012. dtcms.net. All Rights Reserved.</webcopyright> <webpath>/</webpath> <webmanagepath>admin</webmanagepath> <webstatus>1</webstatus> <webclosereason>网站正在维护中,请稍候访问……</webclosereason> <webcountcode><script src="http://s24.cnzz.com/stat.PHP?id=1996164&web_id=1996164&show=pic" language="JavaScript"></script></webcountcode> <staticstatus>1</staticstatus> <staticextension>html</staticextension> <memberstatus>1</memberstatus> <commentstatus>0</commentstatus> <logstatus>1</logstatus> <emailstmp>smtp.qq.com</emailstmp> <emailport>25</emailport> <emailfrom>info@it134.cn</emailfrom> <emailusername>info@it134.cn</emailusername> <emailpassword>EA4C94A47ED87546</emailpassword> <emailnickname>动力启航</emailnickname> <attachpath>upload</attachpath> <attachextension>gif,zip,txt</attachextension> <attachsave>2</attachsave> <attachfilesize>51200</attachfilesize> <attachimgsize>10240</attachimgsize> <attachimgmaxheight>800</attachimgmaxheight> <attachimgmaxwidth>800</attachimgmaxwidth> <thumbnailheight>300</thumbnailheight> <thumbnailwidth>300</thumbnailwidth> <watermarktype>2</watermarktype> <watermarkposition>9</watermarkposition> <watermarkimgquality>80</watermarkimgquality> <watermarkpic>watermark.png</watermarkpic> <watermarktransparency>5</watermarktransparency> <watermarktext>动力启航</watermarktext> <watermarkfont>Tahoma</watermarkfont> <watermarkfontsize>12</watermarkfontsize> <templateskin>green</templateskin> <sysdatabaseprefix>dt_</sysdatabaseprefix> <sysencryptstring>DTcms</sysencryptstring> </siteconfig>
部分代码:
/// <summary> /// 反序列化 /// </summary> /// <param name="type">对象类型</param> /// <param name="filename">文件路径</param> /// <returns></returns> public static object Load(Type type,string filename) { FileStream fs = null; try { // open the stream... fs = new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(type); return serializer.Deserialize(fs); } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } } /// <summary> /// 序列化 /// </summary> /// <param name="obj">对象</param> /// <param name="filename">文件路径</param> public static void Save(object obj,string filename) { FileStream fs = null; // serialize it... try { fs = new FileStream(filename,FileMode.Create,FileAccess.Write,FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(fs,obj); } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } }
/// <summary> /// 读取站点配置文件 /// </summary> public Model.siteconfig loadConfig(string configFilePath) { return (Model.siteconfig)SerializationHelper.Load(typeof(Model.siteconfig),configFilePath); } /// <summary> /// 写入站点配置文件 /// </summary> public Model.siteconfig saveConifg(Model.siteconfig model,string configFilePath) { lock (lockHelper) { SerializationHelper.Save(model,configFilePath); } return model; }原文链接:https://www.f2er.com/xml/300448.html