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;
    }
  • 相关阅读:
    诺基亚为 Qt 增添 LGPL 授权选择
    Web Beans (JSR299): Q&amp;A with Specification Lead Gavin King
    Web Beans (JSR299): Q&amp;A with Specification Lead Gavin King
    诺基亚为 Qt 增添 LGPL 授权选择
    使用 Hibernate 进行大数据量的性能测试
    略谈如何在对话框创建视图类画图
    JBoss Seam 框架下的单元测试
    领域模型设计讨论与研究
    JBoss Seam 框架下的单元测试
    The use of FS/GS registers
  • 原文地址:https://www.cnblogs.com/nanfei/p/2685973.html
Copyright © 2011-2022 走看看