是否可以从xml文本创建ConfigurationElement?

时间:2015-10-01 20:18:39

标签: c# xml configuration configurationsection configurationelement

我们有一个继承自SignalConfigurationElement ConfigurationProperty的自定义类,并使用SignalConfigurationElement属性定义了一堆属性。

ConfigurationManager.GetSection()类是更大的配置元素层次结构的一部分,并且没有构造函数。我能够通过SystemConfiguration调用检索整个配置,提供根元素的名称<configSections>,该名称在app.config文件的SignalConfigurationElement中定义。

我无法控制自定义配置元素,因此我无法更改它们以提供构造函数。我也无法修改app.config,因为它被更大的应用程序使用。

在给定<signals>条目的XML字符串的情况下,是否可以创建ConfigurationManager.GetSection的实例或集合?该类没有构造函数,因此我假设我们的其他应用程序使用<configSections> <section name="SystemConfiguration" type="Fully.Qualified.Namespace.SystemConfiguration, SystemConfiguration"/> </configSections> <SystemConfiguration id="System1" name="System 1"> <equipments> <clear /> <add id="Equipment11" equipmentType="EQ"> <signals> <clear /> <add id="EQ11Signal1" signalId="EQ11Signal1" type="Version" /> <add id="EQ11Signal2" signalId="EQ11Signal2" type="Status" /> <add id="EQ11Signal3" signalId="EQ11Signal3" type="Status" /> </signals> </add> <add id="Equipment21" equipmentType="EQ"> <signals> <clear /> <add id="EQ21Signal1" signalId="EQ21Signal1" type="Version" /> <add id="EQ21Signal2" signalId="EQ21Signal2" type="Status" /> <add id="EQ21Signal3" signalId="EQ21Signal3" type="Status" /> </signals> </add> </equipments> <!-- And a whole lot more. Somewhere in the avenue of 30,000 <signals> entries.--> </SystemConfiguration> 调用来检索整个配置(不是我想要的)使用反射来创建其实例。

代码(完全无法改变任何内容。):

App.Config中

public class SystemConfigurationSection : ConfigurationSection
{
/// <summary>
/// Determines the XML tag that will contain this Configuration Section in an .config file.
/// </summary>
public const string SystemConfigurationSectionName = "SystemConfiguration";

/// <summary>
/// Instance factory method for an instance of the Configuration Section creation.
/// </summary>
/// <returns>
/// Instance of the System Configuration section created based on the .config file of the application.
/// </returns>
public static SystemConfigurationSection GetSystemConfigurationSection()
{
    SystemConfigurationSection result =
        (SystemConfigurationSection) ConfigurationManager.GetSection(SystemConfigurationSectionName);
    return result;
}

/// <summary>
/// Represents the XML attribute used to store ID of the System.
/// </summary>
[ConfigurationProperty(IdConfigurationElementName, IsRequired = true)]
public string Id
{
    get { return (string) this[IdConfigurationElementName]; }
    set { this[IdConfigurationElementName] = value; }
}

/// <summary>
/// Determines name of the XML attribute that will contain ID of the System.
/// </summary>
public const string IdConfigurationElementName = "id";

/// <summary>
/// Represents the XML attribute used to store Name of the System.
/// </summary>
[ConfigurationProperty(NameConfigurationElementName, IsRequired = true)]
public string Name
{
    get { return (string) this[NameConfigurationElementName]; }
    set { this[NameConfigurationElementName] = value; }
}

/// <summary>
/// Determines name of the XML attribute that will contain Name of the System.
/// </summary>
public const string NameConfigurationElementName = "name";

/// <summary>
/// Represents the XML attribute used to store Description of the System
/// </summary>
[ConfigurationProperty(DescriptionConfigurationElementName, IsRequired = false, DefaultValue = "")]
public string Description
{
    get { return (string) this[DescriptionConfigurationElementName]; }
    set { this[DescriptionConfigurationElementName] = value; }
}

/// <summary>
/// Determines name of the XML attribute that will contain Name of the System.
/// </summary>
public const string DescriptionConfigurationElementName = "description";

/// <summary>
/// Represents the collection of the System's Equipments as they are described in the .config file.
/// </summary>
[ConfigurationProperty(EquipmentsConfigurationElementCollectionName, IsDefaultCollection = false)]
[ConfigurationCollection(typeof (EquipmentConfigurationElementCollection), AddItemName = "add",
    ClearItemsName = "clear", RemoveItemName = "remove")]
public EquipmentConfigurationElementCollection Equipments
{
    get { return (EquipmentConfigurationElementCollection) base[EquipmentsConfigurationElementCollectionName]; }
}

/// <summary>
/// Determines name of the XML tag that will contain collection of the System's Equipments.
/// </summary>
public const string EquipmentsConfigurationElementCollectionName = "equipments";

}

类:

/// <summary>
/// Extends the standard .Net ConfigurationElementCollection re-definind commectio manipulation members and making them strongly-typed.
/// </summary>
/// <typeparam name="TElementType">Type of the Configuration Elements that can be included into the collection.</typeparam>
public class ConfigurationElementCollectionBase<TElementType> : ConfigurationElementCollection, IEnumerable<TElementType>
where TElementType : ConfigurationElement, new()
{
/// <summary>
/// Makes the addition operation public.
/// </summary>
/// <param name="customElement">Configuration element to add to the collection.</param>
public virtual void Add(TElementType customElement)
{
    BaseAdd(customElement);
}

/// <summary>
/// Overrides the base implementation of the overloaded method masking an exception throwing.
/// </summary>
/// <param name="element">Configuration element to add.</param>
protected override void BaseAdd(ConfigurationElement element)
{
    BaseAdd(element, false);
}

/// <summary>
/// Overrides the base property hardcoding the returned value.
/// </summary>
public override ConfigurationElementCollectionType CollectionType
{
    get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
}

/// <summary>
/// Overrides the base implementation of the instance factory method.
/// </summary>
/// <returns>A new instance of the Configuration Element type determined by the type parameter.</returns>
protected override ConfigurationElement CreateNewElement()
{
    return new TElementType();
}

/// <summary>
/// Overrides the base implementation of the method determining the indexing algorithm used in the collection.
/// </summary>
/// <param name="element">The configuration element to get index of.</param>
/// <returns></returns>
protected override object GetElementKey(ConfigurationElement element)
{
    return ((TElementType)element);
}

/// <summary>
/// Collection's element accessor by index property.
/// </summary>
/// <param name="index">Index of the desired element in the collection.</param>
/// <returns>The requested collection element if exists.</returns>
public TElementType this[int index]
{
    get { return (TElementType)BaseGet(index); }
    set
    {
        if (BaseGet(index) != null)
        {
            BaseRemoveAt(index);
        }
        BaseAdd(index, value);
    }
}

/// <summary>
/// Overrides the collection's element accessor by key property.
/// </summary>
/// <param name="id">Key of the desired collection element.</param>
/// <returns>The requested collection element if exists</returns>
public new TElementType this[string id]
{
    get { return (TElementType)BaseGet(id); }
}

/// <summary>
/// Implements a standard collection method looking for an element in the collection and returning the element's index if found.
/// </summary>
/// <param name="element">The element to look for.</param>
/// <returns>Index of the element in the collection if exists.</returns>
public int GetIndexOf(TElementType element)
{
    return BaseIndexOf(element);
}

/// <summary>
/// Implements a standard collection method removing an element from the collection.
/// </summary>
/// <param name="url">The element to be removed from the collection.</param>
public void Remove(TElementType url)
{
    if (BaseIndexOf(url) >= 0)
        BaseRemove(url);
}

/// <summary>
/// Implements the standard collection member removing an element from the collection by the element's index.
/// </summary>
/// <param name="index">Index of the element to be removed from the collection.</param>
public void RemoveAt(int index)
{
    BaseRemoveAt(index);
}

/// <summary>
/// Implements a standard collection method removing an element by the element's key.
/// </summary>
/// <param name="id">Key of the element to be removed from the collection.</param>
public void Remove(string id)
{
    BaseRemove(id);
}

/// <summary>
/// Implements the standard collection method that clears the collection.
/// </summary>
public void Clear()
{
    BaseClear();
}


public new IEnumerator<TElementType> GetEnumerator()
{
    for (int i = 0; i < Count; i++)
    {
        yield return this[i];
    }
}

public class EquipmentConfigurationElement : ConfigurationElement
{
    /// <summary>
    /// Represents the collection of the Equipment Unit's Signals as they are described in the .config file.
    /// </summary>
    [ConfigurationProperty(signalsConfigurationElementCollectionName, IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(SignalConfigurationElementCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
    public SignalConfigurationElementCollection Signals
    {
        get
        {
            return (SignalConfigurationElementCollection)base[signalsConfigurationElementCollectionName];
        }
    }
    /// <summary>
    /// Determines name of the XML tag that will contain collection of the Equipment Unit's Signals.
    /// </summary>
    private const string signalsConfigurationElementCollectionName = "signals";

}

/// <summary>
/// Represents a type-safe collection of Equipment Unit Configuration Elements.
/// </summary>
public class EquipmentConfigurationElementCollection : ConfigurationElementCollectionBase<EquipmentConfigurationElement>
{
}

/// <summary>
/// Represensts a Signal's configuration element
/// </summary>
/// <remarks>
/// As the class is derived from ConfigurationElementBase, a Signal's configuration element will expect "is", "name", and "description" XML attributes defined in the configuration file.
/// </remarks>
public sealed class SignalConfigurationElement : ConfigurationElement
{

    /// <summary>
    /// Represents an XML attribute used to determine type of the Signal.
    /// </summary>
    /// <remarks>
    /// The attribute is expected to have a string value which is equal to one of SignalType enumeration member names: "Status" or "Command".
    /// </remarks>
    [ConfigurationProperty(typeConfigurationElementName, IsRequired = false, DefaultValue = "status")]
    public string Type
    {
        get { return (string) this[typeConfigurationElementName]; }
        set { this[typeConfigurationElementName] = value; }
    }

    /// <summary>
    /// Determines name of the XML attribute that will contain type of the Signal.
    /// </summary>
    private const string typeConfigurationElementName = "type";
}

/// <summary>
/// Represents a type-safe collection of Signal Configuration Elements.
/// </summary>
public class SignalConfigurationElementCollection : ConfigurationElementCollectionBase<SignalConfigurationElement>
{
}

         Try
            Dim MyDb As New Database_Connection
            Dim query As String
            query = "select phone_number from schedule where Phone_Number = '" & frmViewSchedule.dgvSchedule.SelectedRows(3).Cells(0).Value & "'"
                Dim myReader As OdbcDataReader = MyDb.ExecuteQuery(query)

            myReader.Read()

             If reader.HasRows Then
               dim ph_number as string = myReader.Item(0)
              .
              .
              .
             End if             
                myReader.Close()
                MyDb.Dispose()
            Catch ex As System.Data.Odbc.OdbcException
                'MessageBox.Show(ex.ToString)
            End Try

1 个答案:

答案 0 :(得分:0)

这可以通过黑暗的反思艺术来实现。鉴于您的问题中显示的XML,您可以这样做:

    var configXml = GetAppConfigXml(); // Returns the XML shown in your question.

    var config = (SystemConfigurationSection)Activator.CreateInstance(typeof(SystemConfigurationSection), true);

    using (var sr = new StringReader(configXml))
    using (var xmlReader = XmlReader.Create(sr))
    {
        if (xmlReader.ReadToDescendant("SystemConfiguration"))
            using (var subReader = xmlReader.ReadSubtree())
            {
                var dynMethod = config.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(XmlReader) }, null);
                dynMethod.Invoke(config, new object[] { subReader });
            }
    }
    Debug.Assert(config.Equipments.Count == 2); // No assert

参考:source for ConfigurationSection.DeserializeSection

顺便说一句,附加到您的问题的配置类与XML不匹配。缺少某些属性,与XML中的属性对应的属性必须为IsKey = true。如果XML与配置类不匹配,DeserializeSection将抛出异常。