2016-12-24 23 views
0

我需要新設置手動合併年長user.config,和現在我只想老值加載到一個字典:如何自定義user.config XML加載到一個字典

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <userSettings> 
     <myprog.Properties.Settings> 
      <setting name="openkey" serializeAs="String"> 
       <value>o</value> 
      </setting> 
      <setting name="licenseAccepted" serializeAs="String"> 
       <value>True</value> 
      </setting> 

代碼:

Dictionary<string, string> myDictionary = new Dictionary<string, string>(); 
XmlDocument document = new XmlDocument(); 
document.Load(OlderSettingLocation); 
XmlNodeList s = document.SelectNodes("/configuration/userSettings/myprog.Properties.Settings/setting"); 
      foreach (XmlNode node in s) 
      { 
       myDictionary.Add(node.Attributes["name"].Value, node.Attributes["value"].Value); 
      } 

這導致node.Attributes [「名稱」]。值是「設定」,而不是在第一回路「打開項」,而和值均爲空下面

+0

你能給出一個更完整的示例與多個設置? – jdweng

回答

1

見代碼。我提供了兩種解決方案首先如果每個密鑰都是唯一的,其次是每個密鑰有多個值。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 

      XDocument doc = XDocument.Load(FILENAME); 

      Dictionary<string, string> dict1 = doc.Descendants("setting").Select(x => new { 
       name = (string)x.Attribute("name"), 
       value = (string)x.Element("value") 
      }).GroupBy(x => x.name, y => y.value) 
      .ToDictionary(x => x.Key, y => y.FirstOrDefault()); 


      Dictionary<string, List<string>> dict2 = doc.Descendants("setting").Select(x => new { 
       name = (string)x.Attribute("name"), 
       value = (string)x.Element("value") 
      }).GroupBy(x => x.name, y => y.value) 
      .ToDictionary(x => x.Key, y => y.ToList()); 

     } 
    } 
}