【问题标题】:Can I add a textnode instead of an attribute in a .NET configurationsection?我可以在 .NET 配置部分中添加文本节点而不是属性吗?
【发布时间】:2011-07-02 00:21:14
【问题描述】:

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

<customSection name="My section" />

我想要的是把它写成一个文本节点(我不确定这是否是正确的术语?)像这样:

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

我当前的 customSection 类如下所示:

public class CustomSection: ConfigurationSection {

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

}

我应该怎么做才能使它成为一个文本节点?

【问题讨论】:

  • 为什么微软一开始就不允许这样做?

标签: c# asp.net configuration web-config


【解决方案1】:

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

类代码简单:

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; }
    }
}

【讨论】:

    【解决方案2】:

    如果您希望能够同时拥有属性和文本内容,例如

    <customsection>
          <name key="val">My Section</name>
    </customSection>
    

    然后你可以像这样覆盖DeserializeElement

    protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
    {
        int count = reader.AttributeCount;
        //First get the attributes
        string attrName;
        for (int i = 0; i < count; i++)
        {
            reader.MoveToAttribute(i);
            attrName = reader.Name;
            this[attrName] = reader.Value;
        }
        //then get the text content
        reader.MoveToElement();
        text = reader.ReadElementContentAsString();
    }
    

    希望这会有所帮助。

    【讨论】:

    • 这非常有帮助,但让我想知道为什么将 .NET 配置文件应用于对象是一项如此繁重的工作。将此与从 Xml 到 Object 的 JAXB 解组比较,如果您定义一个具有明显命名属性的对象,则不必编写 anything 代码。鉴于 API 的优雅和 LINQ、lambda 和 ExpressionTree 部分,我对 ConfigurationManager 的对象模型的原始程度感到震惊(以及将配置应用于对象需要多少代码。)有什么更新了吗?