Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a textnode instead of an attribute in a .NET configurationsection?

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

<customSection name="My section" />

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>

My current customSection class looks like this:

public class CustomSection: ConfigurationSection {

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

}

What should I do to make it a textnode?

like image 872
Kristian Frost Avatar asked Feb 22 '11 13:02

Kristian Frost


2 Answers

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).

The class code is brief:

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; }
    }
}
like image 132
CalebD Avatar answered Oct 20 '22 09:10

CalebD


If you want to be able to have both attributes as well as text content e.g.

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

Then you can override DeserializeElement like so:

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

Hope this helps.

like image 32
frezq Avatar answered Oct 20 '22 09:10

frezq