XML文件到嵌套字典的字典

时间:2010-09-30 21:32:16

标签: c# xml dictionary

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

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

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

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数据的最佳方法,我会更好吗

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

例如?
2)成功填充相关词典有一些问题

1 个答案:

答案 0 :(得分:1)

您希望将LINQ-to-XML用于.NET中的所有XML:

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));

构造嵌套字典就好像result一样创建如下:

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" } } },
};