是否可以在.NET配置节中添加文本节点而不是属性? [英] Can I add a textnode instead of an attribute in a .NET configurationsection?

查看:61
本文介绍了是否可以在.NET配置节中添加文本节点而不是属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个.NET自定义配置部分,如下所示:

I currently have a .NET custom configurationsection that looks like this:

<customSection name="My section" />

我要写的是一个textnode(我不确定这是否正确字样?):

What I want is to write it as a textnode (I'm not sure if this is the correct term?) like this:

<customSection>
  <name>My Section</name>
</customSection>

我当前的customSection类如下:

My current customSection class looks like this:

public class CustomSection: ConfigurationSection {

  [ConfigurationProperty("name")]
  public String Name {
    get {
      return (String)this["name"];
    }
  }

}

应该做什么

推荐答案

一些研究表明,现有的配置类不支持该类型的元素?而不创建自定义类来处理它。 这篇CodeProject 文章介绍了如何创建新的 ConfigurationTextElement 通用类,可以将序列化的字符串解析为对象(包括字符串,这就是本文显示的内容)。

A bit of research suggests that the existing configuration classes do not support that type of element without creating a custom class to handle it. This CodeProject article covers creating a new ConfigurationTextElement class that is generic and can parse a serialized string into an object (including a string, which is what the article shows).

该类代码很简短:

using System.Collections.Generic;
using System.Configuration;
using System.Xml;

public class ConfigurationTextElement<T> : ConfigurationElement
{
    private T _value;
    protected override void DeserializeElement(XmlReader reader, 
                            bool serializeCollectionKey)
    {
        _value = (T)reader.ReadElementContentAs(typeof(T), null);
    }

    public T Value
    {
        get { return _value; }
    }
}

这篇关于是否可以在.NET配置节中添加文本节点而不是属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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