Kri*_*ost 17 c# asp.net configuration web-config
我目前有一个.NET自定义配置部分,如下所示:
<customSection name="My section" />
我想要的是将它写为textnode(我不确定这是否是正确的术语?),如下所示:
<customSection>
  <name>My Section</name>
</customSection>
我当前的customSection类看起来像这样:
public class CustomSection: ConfigurationSection {
  [ConfigurationProperty("name")]
  public String Name {
    get {
      return (String)this["name"];
    }
  }
}
我该怎么做才能使它成为一个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; }
    }
}
fre*_*ezq 12
如果您希望能够同时拥有属性和文本内容,例如
<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();
}
希望这可以帮助.
| 归档时间: | 
 | 
| 查看次数: | 3516 次 | 
| 最近记录: |