How to Read a Configuration Section from XML in a Database?

后端 未结 5 1617
失恋的感觉
失恋的感觉 2021-02-01 04:01

I have a Config class like this:

public class MyConfig : ConfigurationSection
{
        [ConfigurationProperty(\"MyProperty\", IsRequired = true)]
        public         


        
5条回答
  •  情歌与酒
    2021-02-01 04:49

    If you need to get any System.Configuration.ConfigurationSection stored in database, you may consider writing generic section reader like this:

        
    public class ConfigurationSectionReader where T : ConfigurationSection, new()
    {
        public T GetSection( string sectionXml ) 
        {
            T section = new T();
            using ( StringReader stringReader = new StringReader( sectionXml ) )
            using ( XmlReader reader = XmlReader.Create( stringReader, new XmlReaderSettings() { CloseInput = true } ) )
            {
                reader.Read();
                section.GetType().GetMethod( "DeserializeElement", BindingFlags.NonPublic | BindingFlags.Instance ).Invoke( section, new object[] { reader, true } );
            }
            return section;
        }
    }
        
    

    This will work for all classes that override DeserializeElement method. e.g.

        
    protected override void DeserializeElement( XmlReader reader, bool serializeCollectionKey )
    {
        XmlDocument document = new XmlDocument();
        document.LoadXml( reader.ReadOuterXml() );
        MyProperty = document.DocumentElement.HasAttribute( "MyProperty" )
            ? document.DocumentElement.Attributes[ "MyProperty" ].Value
            : string.Empty;
    }
        
    

    Than you could get a section like this:

        
    var reader = new ConfigurationSectionReader();
    var section = reader.GetSection( sectionXml ); // where sectionXml is the XML string retrieved from the DB
        
    

提交回复
热议问题