我需要手动将较旧的user.config与新设置合并,现在我只想将旧值加载到字典中:
<?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 [“ name”]。Value在第一个循环中是“设置”而不是“ openkey”,并且值是null
请参见下面的代码。我提供了两种解决方案。首先是每个键都是唯一的,其次是每个键有多个值。
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());
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句