• 自定义配置节与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;
    }
  • 相关阅读:
    编程珠玑第二章阅读笔记
    第四周学习进度博客
    python的文件操作
    python通过pymysql实现数据库的增删改查
    python爬取疫情数据详解
    python基本知识点if、while、等等
    apache使用总结
    slf4j的总结
    log4j2使用总结
    安全测试总结
  • 原文地址:https://www.cnblogs.com/nanfei/p/2685973.html
Copyright © 2020-2023  润新知