2013-01-24 27 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從配置文件中獲取該值時真的有用。