2011-06-02 63 views
10

如何从App.config中读取此自定义配置?如何从App.config中读取此自定义配置?

<root name="myRoot" type="rootType"> 
    <element name="myName" type="myType" /> 
    <element name="hisName" type="hisType" /> 
    <element name="yourName" type="yourType" /> 
    </root> 

而不是这样的:

<root name="myRoot" type="rootType"> 
    <elements> 
    <element name="myName" type="myType" /> 
    <element name="hisName" type="hisType" /> 
    <element name="yourName" type="yourType" /> 
    </elements> 
    </root> 
+1

如果这些答案不能完全帮助您,请提供其他信息,以便我们能够提供进一步的帮助。 – Haukman 2011-06-16 05:26:29

回答

31

为了使您的收藏元素直接的父元素(而不是一个子集元素)内坐下,你需要重新定义您ConfigurationProperty。例如,假设我有一个集合元素,如:

public class TestConfigurationElement : ConfigurationElement 
{ 
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)] 
    public string Name 
    { 
     get { return (string)this["name"]; } 
    } 
} 

和收集,如:

[ConfigurationCollection(typeof(TestConfigurationElement), AddItemName = "test")] 
public class TestConfigurationElementCollection : ConfigurationElementCollection 
{ 
    protected override ConfigurationElement CreateNewElement() 
    { 
     return new TestConfigurationElement(); 
    } 

    protected override object GetElementKey(ConfigurationElement element) 
    { 
     return ((TestConfigurationElement)element).Name; 
    } 
} 

我需要定义父节/元素:

public class TestConfigurationSection : ConfigurationSection 
{ 
    [ConfigurationProperty("", IsDefaultCollection = true)] 
    public TestConfigurationElementCollection Tests 
    { 
     get { return (TestConfigurationElementCollection)this[""]; } 
    } 
} 

请注意0​​属性。给它一个空的名字,并设置为默认集合允许我定义我的配置,如:

<testConfig> 
    <test name="One" /> 
    <test name="Two" /> 
</testConfig> 

相反的:

<testConfig> 
    <tests> 
    <test name="One" /> 
    <test name="Two" /> 
    </tests> 
</testConfig> 
4

因为这不是你要打开配置文件的XML文档,然后拉出部分(使用XPath为标准配置文件格式例)。与此打开文档:

// Load the app.config file 
XmlDocument xml = new XmlDocument(); 
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); 
0

我认为你可以使用

  XmlDocument appSettingsDoc = new XmlDocument(); 
      appSettingsDoc.Load(Assembly.GetExecutingAssembly().Location + ".config"); 
      XmlNode node = appSettingsDoc.SelectSingleNode("//appSettings"); 

      XmlElement element= (XmlElement)node.SelectSingleNode(string.Format("//add[@name='{0}']", "myname")); 
      string typeValue = element.GetAttribute("type"); 

希望这可以解决您的问题。快乐编码。 :)

相关问题