XML文件到带有嵌套字典的字典 [英] XML file to dictionary with nested dictionary

查看:99
本文介绍了XML文件到带有嵌套字典的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#中的XmlTextReader读取XML文件的内容,该文件具有以下结构:

I'm attempting to read the content of a XML file, using XmlTextReader in C#, that has the following structure:

<root>
  <person id="0">
    <a1>val</a1>
    <a2>val</a2>
  </person>
  <person id="1">
    <a1>val</a1>
    <a2>val</a2>
  </person>
</root>

我希望将文件读入嵌套字典中:

I'm looking to read the file into a nested dictionary:

Dictionary<string, Dictionary<string, string>> xmldata = new Dictionary<string, Dictionary<string, string>>();

希望生产:

xmldata = {0 => {a1 => val, a2 => val}, 1 => {a1 => val, a2 => val}}

问题:

1 )不确定这是存储读入的xml数据的最佳方法,

1) Not sure this is the best method for storing the xml data read in, would I be better with

<a x="1"></a><a x="2"></a>

例如?

2)成功填充相关字典时遇到一些问题

for example?
2) Having a few problems successfully populating the relavent dictionaries

推荐答案

您要使用 LINQ-to-XML 用于.NET中XML的所有内容:

You want to use LINQ-to-XML for all things XML in .NET:

var doc = XDocument.Parse(@"<root>
  <person id=""0"">
    <a1>val</a1>
    <a2>val</a2>
  </person>
  <person id=""1"">
    <a1>val</a1>
    <a2>val</a2>
  </person>
</root>");

var result = doc.Root
                .Elements()
                .ToDictionary(
                    e => e.Attribute("id"),
                    e => e.Elements()
                          .ToDictionary(
                              f => f.Name.LocalName,
                              f => f.Value));

结构嵌套字典就像结果是这样创建的:

The constructs nested dictionaries like as if result was created like this:

var result = new Dictionary<string, Dictionary<string, string>>
{
    { "0", new Dictionary<string, string> { { "a1", "val" }, { "a2", "val" } } },
    { "1", new Dictionary<string, string> { { "a1", "val" }, { "a2", "val" } } },
};

这篇关于XML文件到带有嵌套字典的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆