我想你會需要重寫OnDeserializeUnrecognizedElement。請看看this answer。
使用上面的方法,這裏是我是如何能夠達到您的要求的結果: -
我SomeConfigSection類如下所示: -
public class SomeConfigSection : ConfigurationSection
{
[ConfigurationProperty("SomeConfig", IsRequired = true)]
public string SomeConfig
{
get { return (string)base["SomeConfig"]; }
set { base["SomeConfig"] = value; }
}
XElement _SomeParam;
public XElement SomeParam
{
get { return _SomeParam; }
}
protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader)
{
if (elementName == "SomeParam")
{
_SomeParam = (XElement)XElement.ReadFrom(reader);
return true;
}
else
return base.OnDeserializeUnrecognizedElement(elementName, reader);
}
}
我的App.config看起來是這樣的: -
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="SomeConfig" type="ConfigTest.SomeConfigSection,ConfigTest" />
</configSections>
<SomeConfig>
<SomeParam>SomeText</SomeParam>
</SomeConfig>
</configuration>
在我的形式,下面是我如何讀值: -
SomeConfigSection configSection = ConfigurationManager.GetSection("SomeConfig") as SomeConfigSection;
if (configSection != null)
label1.Text= configSection.SomeParam.Value;
希望這會有所幫助!
[檢查] [1]這些鏈接可能會幫助你。 [1]:http://stackoverflow.com/questions/7044871/how-do-i-use-net-custom-configurationelement-properties-on-descendent-elements –
@H。瑪希達,不幸的是,它不能,因爲我需要將該值存儲爲元素體而不是元素屬性。 – user626528