Can I add a textnode instead of an attribute in a

2020-08-09 07:23发布

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?

2条回答
看我几分像从前
2楼-- · 2020-08-09 08:13

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; }
    }
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-08-09 08:21

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.

查看更多
登录 后发表回答