自定义配置节与XML反序列化并用
web.config
<?xml version="1.0"?> <configuration> <configSections> <section name="menus" type="XmlSerializerPlus.MenuSectionHandler"/> </configSections> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <menus> <menu name="a"> <children> <menu name="a1" /> <menu name="a2" /> <menu name="a3" /> </children> </menu> <menu name="b"> <children> <menu name="b1" /> <menu name="b2" /> <menu name="b3"> <children> <menu name="b31" /> <menu name="b32" /> <menu name="b33" /> </children> </menu> </children> </menu> </menus> </configuration>
Menu.cs
using System.Xml.Serialization; using System.Xml.Schema; [XmlRootAttribute(ElementName = "menus", Namespace = "", IsNullable = false)] public class Menus { [XmlElementAttribute("menu", Form = XmlSchemaForm.Unqualified)] public Menu[] Items { get; set; } } [XmlTypeAttribute(AnonymousType = true)] public class Menu { [XmlAttributeAttribute("name")] public string Name { get; set; } [XmlArrayAttribute("children")] [XmlArrayItemAttribute("menu", typeof(Menu), Form = XmlSchemaForm.Unqualified, IsNullable = true)] public Menu[] Children { get; set; }
MenuSectionHandler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.IO; using System.Xml.Serialization; namespace XmlSerializerPlus { public class MenuSectionHandler : IConfigurationSectionHandler { public object Create(object parent, object configContext, System.Xml.XmlNode section) { using (StringReader sr = new StringReader(section.OuterXml)) { var serializer = new XmlSerializer(typeof(Menus)); return serializer.Deserialize(sr); } } } }
测试代码:
protected void Page_Load(object sender, EventArgs e) { Menus menus = ConfigurationManager.GetSection("menus") as Menus; }
桂棹兮兰桨,击空明兮溯流光。