C# xml 具有多个部分到字典的转换
C# xml with multiple sections to dictionary conversion
我有一个类似于
的配置文件
<configuration>
<setings1>
<a>False</a>
<c>True</c>
</setings1>
<Settings2>
<b>10</b>
</Settings2>
</configuration>
如何转换为字典(string,list(string,string)) 即设置为键,元素为子值
您可以尝试枚举 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);
}
List<T>
在C#中不支持两个泛型类型参数,所以你不能像List<string,string>
那样声明它。
您可以使用元组列表,如上面的示例或创建您自己的对象来表示键和值或使用内置 KeyValuePair<TKey,TValue>
class
使用 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:\temp\test.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());
}
}
}
我有一个类似于
的配置文件 <configuration>
<setings1>
<a>False</a>
<c>True</c>
</setings1>
<Settings2>
<b>10</b>
</Settings2>
</configuration>
如何转换为字典(string,list(string,string)) 即设置为键,元素为子值
您可以尝试枚举 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);
}
List<T>
在C#中不支持两个泛型类型参数,所以你不能像List<string,string>
那样声明它。
您可以使用元组列表,如上面的示例或创建您自己的对象来表示键和值或使用内置 KeyValuePair<TKey,TValue>
class
使用 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:\temp\test.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());
}
}
}