zoukankan      html  css  js  c++  java
  • 使用.NET 反射机制(Reflecttion)读取和保存Xml配置文档

    在 .net 中使用 XmlDocument 对 xml 进行读取和保存,就好象使用使用 ADO.NET 访问数据库一样需要编写大量的繁琐代码,现在开发数据库程序基本上都使用ORM 框架简化工作,同样也可以类似的使用反射机制将 XML 配置文件转化为相应的 对象,使用的使用直接调用对象就可以。

    下面根据一个简单的实例说明下思路

    <?xml version="1.0" encoding="utf-8"?>
    <root>
      <templates>
        <template id="100" name="模板1">
          <header fontname="宋体" fontsize="14" align="Left" content=""/>
        </template>
       <template id="100">
          <header fontname="宋体" fontsize="14" align="Left" content=""/>
        </template>
      </templates>
    </root>
    

      上面是一个简单配置文件,根据这个XML的结构编写下面的相应对象

     [XmlFile("XXTemplate.xml", "root", "配置文件的名称")]
     public class XXTemplate
    {    
         [XmlCollection(typeof(List<XXTemplateItem>), typeof(XXTemplateItem), "templates", "")]
    public List<XXTemplateItem> Templates { get; set; }
     
    [XmlItem(typeof(PrintTemplateItem), "template", "")]
    public class XXTemplateItem
    {
         [XmlProperty("id", typeof(string), "")]
      public string Id {get;set;}
          [XmlProperty("name", typeof(string), "")]
    public string Name {get;set;}
       [XmlItem(typeof(XXTemplateItemHeader), "header", "")]
      public XXTemplateItemHeader Header { get; set; }
    }
     [XmlItem(typeof(XXTemplateItemHeader), "header", "")]
    public class XXTemplateItemHeader
    {  
        [XmlProperty("fontname", typeof(string), "")]
    public string Fontname {get;set;}
     }
     

    这样就在 XML 和对象之间建立了映射,最后创建一个通用的 映射管理类 负责读取XML 文档转化为 对象 和 在修改对象后将状态保存到XML文档中。

    在这个处理过程中,主要是使用到了 .net 的 反射机制 (Reflection) 和 属性(Attribute)

  • 相关阅读:
    Java注解
    java反射简单入门
    java泛型反射
    BeanUtils.populate的作用
    适配器模式
    原型模式
    抽象工厂模式
    工厂方法模式
    建造者模式
    单例模式
  • 原文地址:https://www.cnblogs.com/babietongtianta/p/2346407.html
Copyright © 2011-2022 走看看