C# 为什么可以';我不能将属性转换为嵌套元素吗?
我正在读取“App.config”中的设置。我刚刚了解了如何使用C# 为什么可以';我不能将属性转换为嵌套元素吗?,c#,.net,xml,app-config,C#,.net,Xml,App Config,我正在读取“App.config”中的设置。我刚刚了解了如何使用ConfigurationSection,configurationelement集合和configurationelement App.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="notificationSe
ConfigurationSection
,configurationelement集合
和configurationelement
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="notificationSettingsGroup">
<section name="mailTemplates" type="Project.Lib.Configuration.MailTemplateSection, Project.Lib"
allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" requirePermission="false"/>
</sectionGroup>
</configSections>
<notificationSettingsGroup>
<mailTemplates>
<items>
<mailTemplate name="actionChain" subject="Subject bla-bla">
<body>Body bla-bla</body>
</mailTemplate>
</items>
</mailTemplates>
</notificationSettingsGroup>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
和工作代码:
class Program
{
static void Main(string[] args)
{
Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var mailTemplatesSection =
config.GetSection("notificationSettingsGroup/mailTemplates") as MailTemplateSection;
}
}
当我在xml中将字段声明为属性时,所有这些都可以工作。但当我尝试将属性转换为嵌套元素时,会出现“属性“Body”不是ConfigurationElement”错误
我做错了什么?因为您必须创建自定义类型并从ConfigurationElement派生它们,以便将它们用作配置文件中的元素。所有简单类型始终作为属性编写。 例如:
public class Body : ConfigurationElement
{
[ConfigurationProperty("value", DefaultValue = "Body", IsKey = true, IsRequired = true)]
public string Value{get;set;}
}
这将允许你写作
<body value="some val"/>
在您的配置中。Vladimir,我想在“body”属性中存储大文本,但不想在属性中存储此数据。IMHO,大数据必须存储在标签中。大文本根本不应该存储在App.config中。使用数据库或自定义格式。它可能很容易成为XmlSerializer生成的格式,您可以为其创建类并完全控制数据的序列化方式。令人沮丧的是,有多少次人们不响应原始请求,认为这不是解决方法。在这种情况下,使用元素而不是属性可能有很多原因,比如使用CDATA…请参阅
class Program
{
static void Main(string[] args)
{
Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var mailTemplatesSection =
config.GetSection("notificationSettingsGroup/mailTemplates") as MailTemplateSection;
}
}
public class Body : ConfigurationElement
{
[ConfigurationProperty("value", DefaultValue = "Body", IsKey = true, IsRequired = true)]
public string Value{get;set;}
}
<body value="some val"/>