自定义配置节与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;
}

posted on   空明流光  阅读(298)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2012年9月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 1 2 3 4 5 6
点击右上角即可分享
微信分享提示