Can I add a textnode instead of an attribute in a

2020-08-09 08:07发布

问题:

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?

回答1:

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


回答2:

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.