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?

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

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.


Need Your Help

MySQL and JDBC caching (?) issue with procedure call in Scala

mysql scala stored-procedures jdbc

I'm working on a project that parses text units (referenced as "ngrams") from a string and stores them in a MySQL database.

How can a batch program parse a text data file for values and then save into a csv type file?

parsing csv batch-file findstr

I have a bunch a raw data that really only has four values I care about: DX, DY, Width and Height in addition to the corresponding offset name.