【问题标题】:How to load custom user.config xml into a dictionary如何将自定义 user.config xml 加载到字典中
【发布时间】:2016-12-25 19:43:57
【问题描述】:

我需要手动将旧 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

【问题讨论】:

  • 你能给出一个更完整的具有多个设置的示例吗?

标签: c# xml


【解决方案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());

        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 2017-04-01
    • 2010-10-18
    • 1970-01-01
    • 2011-01-16
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多