2013-01-24 36 views
1

在machine.config文件有通过第三方软件写有元素,因此它看起来像这样:使用XmlDocument读取自定义的machine.config元素?

<configuration> 
    <configSections> 
    ... 
    </configSections> 

    ... 

    <Custom> 
     <Level1> ... 
     </Level1> 

     <Level2> ... 
     </Level2> 

     <Level3> 
      <add key="key_text1" value="s1" /> 
      <add key="key_text2" value="s2" /> 
      <add key="key_text3" value="s3" /> 
     </Level3> 
    </Custom> 
</configuration> 

我想如来自配置/ Custom/Level3节点的“value”属性的值(“s2”),其中key =“key_text2”。到目前为止,我试图从那里打开machine.config中作为XML和工作:

Configuration config = ConfigurationManager.OpenMachineConfiguration(); 
XmlDocument doc = new XmlDocument(); 
doc.LoadXml(config.FilePath); 

不过,我得到XmlException“在根级别的数据是无效的。”我也不知道如何直接使用Configuration类方法来完成这个任务。任何想法,将不胜感激。

回答

2

使用RuntimeEnvironment.SystemConfigurationFile得到的machine.config位置:

XmlDocument doc = new XmlDocument(); 
doc.Load(RuntimeEnvironment.SystemConfigurationFile); 

而且为什么不使用LINQ到XML?

XDocument xdoc = XDocument.Load(RuntimeEnvironment.SystemConfigurationFile); 
var element = xdoc.XPathSelectElement("//Custom/Level3/add[@value='s2']"); 
if (element != null) 
    key = (string)element.Attribute("key"); 
+1

谢谢,非常有用。这两个答案(动物和你的)实际上工作。不过,我不得不使用下面的代码来实现它: var query =“/ configuration/Custom/Level3/add [@ value ='s2']”; var dbElement1 = xdoc.XPathSelectElement(query); string key = dbElement1.Attribute(“value”)。Value;' – w128

+1

@ w128您可以在*'* chars之间粘贴代码 –

1

尝试使用Load()方法而不是LoadXml()

doc.Load(config.FilePath); 

我也高度重视和建议你看一看的XDocument代替的XmlDocument。 LINQ从配置文件中获取该值时真的有用。