我可以在.NET配置部分中添加textnode而不是属性吗?

Kri*_*ost 17 c# asp.net configuration web-config

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

<customSection name="My section" />
Run Code Online (Sandbox Code Playgroud)

我想要的是将它写为textnode(我不确定这是否是正确的术语?),如下所示:

<customSection>
  <name>My Section</name>
</customSection>
Run Code Online (Sandbox Code Playgroud)

我当前的customSection类看起来像这样:

public class CustomSection: ConfigurationSection {

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

}
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能使它成为一个textnode?

Cal*_*ebD 16

一些研究表明,现有的配置类不支持该类型的元素而不创建自定义类来处理它.这篇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; }
    }
}
Run Code Online (Sandbox Code Playgroud)


fre*_*ezq 12

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

<customsection>
      <name key="val">My Section</name>
</customSection>
Run Code Online (Sandbox Code Playgroud)

然后你可以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();
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 这非常有用,但让我想知道为什么将 .NET 配置文件应用于对象是如此繁琐。将此与从 Xml 到 Object 的 JAXB 解组进行比较,如果您定义具有明显命名属性的对象,则不必编写 *任何内容*。鉴于 API 的优雅和 LINQ、lambdas 和 ExpressionTree 部分,我对 ConfigurationManager 的对象模型的原始程度感到震惊(以及将配置应用于对象所需的代码量。)更多更新? (3认同)