zoukankan      html  css  js  c++  java
  • 自定义配置节与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;
    }
  • 相关阅读:
    ios开发函数(数学函数应用)
    苹果的软件/系统盘 网站 http://www.panduoduo.net/u/bd-369186934/2
    iOS-运行时机制
    ios滑动手势全屏(这段代码实现了下一级控制器滑到上一级控制器)
    js正则表达式总结
    text-shadow属性
    css3的box-shadow属性
    white-space属性
    js的sort()方法详解
    搜索框demo
  • 原文地址:https://www.cnblogs.com/nanfei/p/2685973.html
Copyright © 2011-2022 走看看