带有多个节的C#xml到字典的转换



我有一个配置文件,看起来像

<configuration>
<setings1>
<a>False</a>
<c>True</c>
</setings1>
<Settings2>
<b>10</b>
</Settings2>
</configuration>

如何转换为字典(字符串、列表(字符串、字符串((,即设置为关键字,元素为子值

您可以尝试枚举Root节点的子元素作为设置项,然后枚举每个setting元素以获得子值

var document = XDocument.Parse(xml);
var dict = new Dictionary<string, List<(string key, string value)>>();
foreach (var element in document.Root.Elements())
{
var list = new List<(string key, string value)>();
foreach (var child in element.Elements())
{
list.Add((child.Name.ToString(), child.Value));
}
dict.Add(element.Name.ToString(), list);
}

C#中的List<T>不支持两个泛型类型参数,因此不能像List<string,string>那样声明它。

您可以像上面的示例一样使用元组列表,或者创建自己的对象来表示键和值,或者使用内置KeyValuePair<TKey,TValue>

使用XMl Linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication157
{
class Program
{
const string FILENAME = @"c:temptest.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, List<List<string>>> dict = doc.Descendants().Where(x => x.Name.LocalName.ToUpper().StartsWith("SETTINGS"))
.GroupBy(x => x.Name.LocalName.ToUpper(), y => y.Elements().Select(a => new List<string> { a.Name.LocalName, (string)a }).ToList())
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}

最新更新