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;
    }
  • 相关阅读:
    极高效内存池实现 (cpu-cache)
    gles2.0环境的在windows上的建立
    使用OpenGL绘制 shapefile文件 完成最基本的gis操作
    纯C++安卓开发 (ndk)系列之 ---- 常见问题
    如何用 纯C++(ndk)开发安卓应用 ?
    Android-NDK处理用户交互事件
    图解-安卓中调用OpenGL
    图解安卓-c++开发-通过java 调用c++ jni的使用
    搭建安卓开发环境 hello world andriod
    关于socket通讯,如何才能高效?
  • 原文地址:https://www.cnblogs.com/nanfei/p/2685973.html
Copyright © 2011-2022 走看看