如何获取配置元素 [英] How to get configuration element

查看:21
本文介绍了如何获取配置元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

谁能解释我如何从 .config 文件中获取配置元素.我知道如何处理属性而不是元素.例如,我想解析以下内容:

Can anybody explain me how to get configuration element from .config file. I know how to handle attributes but not elements. As example, I want to parse following:

<MySection enabled="true">

 <header><![CDATA[  <div> .... </div>  ]]></header>

 <title> .... </title>

</MySection>

到目前为止,我的 c# 代码如下所示:

My c# code looks like this so far:

 public class MyConfiguration : ConfigurationSection
    { 
        [ConfigurationProperty("enabled", DefaultValue = "true")]
        public bool Enabled
        {
            get { return this["enabled"].ToString().ToLower() == "true" ? true : false;   }
        }

        [ConfigurationProperty("header")]
        public string header
        {
                ???
        }
  }

它适用于属性,我如何处理元素(上面代码中的标题属性)?

It works with attributes, how do I do with elements (header property in above code) ?

推荐答案

我终于找到了一种方法.

I finally found one way to do it.

有 IConfigurationSectionHandler 接口,允许我想要的东西.需要自己写方法

There is IConfigurationSectionHandler interface that allows for things I want. It requires the one to write the method

 public object Create(object parent, object configContext, XmlNode section)

之后,你自己解析 section,这样我就可以毫无问题地获取 XmlElement:

After it, u parse section on your own so I was able to fetch XmlElement's without a problem:

        header  = s["header"]  != null ? s["header"].InnerText   : String.Empty;
        title   = s["title"]   != null ? s["title"].InnerText    : String.Empty;

不利的一面是接口已经过时,但 MSDN 声明它不会从框架的未来版本中删除,因为它在内部使用.

The down side of this is that interface is outdated but MSDN states that it will not be removed from future versions of the frameworks as it is used internally.

这篇关于如何获取配置元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆