Linq to XML - 将节点解析为字典

时间:2013-12-25 12:49:31

标签: c# xml linq

我自己无法想象这一点。我的XML文件如下所示:

<section name="blah">
   <setting1 name="blah">blah</setting1>
   <setting1 name="blah1">blah1</setting1>
</section>

<section name="foo">
   <setting2 name="sth">sth</setting2>
   <setting2 name="sth1">lala</setting2>
</section>

等等。

我想要做的是将每个部分解析为它自己的字典,如下所示:

Dictionary <string, string> foo;
Dictionary <string, string> blah;

XElement xelement = XElement.Load("test.xml");
IEnumerable<XElement> sections = xelement.Elements();
foreach (var section in sections)
{
    switch (section.Attribute("name").Value)
    {
        case "foo":
            foo = ... Something
            break;

        case "blah":
            blah = ... Something
            break;
    }
}

等等。

解析后:

foo["sth1"] <---- contains lala
blah["blah1"] <---- contains blah1

我如何在Linq中实现这一目标?

2 个答案:

答案 0 :(得分:3)

虽然你可以将名称硬编码为变量,但我怀疑你最好使用Dictionary<string, Dictionary<string, string>>

var settings = element.Elements("section")
     .ToDictionary(section => section.Attribute("name").Value,
                   section => section.Elements()
                       .ToDictionary(setting => setting.Attribute("name)".Value,
                                     setting => setting.Value));

Console.WriteLine(settings["foo"]["sth1"]); // lala

这使用对ToDictionary的嵌套调用,您可以在其中指定键和给定任何特定项的值。外部字典的每个元素的值本身就是一个字典,是根据该部分中的元素创建的。

答案 1 :(得分:2)

Dictionary <string, string> foo=new Dictionary<string,string>();
Dictionary <string, string> blah;

XElement xelement = XElement.Load("D:\\x.xml");
IEnumerable<XElement> sections = xelement.Elements();
     foreach (var section in sections)
     {
          switch (section.Attribute("name").Value)
          {
              case "foo":
                    foreach (XElement element in section.Descendants().Where(p => p.HasElements == false))
        {
            int keyInt = 0;
            string keyName = element.Attribute("name").Value;

            while (foo.ContainsKey(keyName))
                keyName = element.Attribute("name") + "_" + keyInt++;

            foo.Add(keyName, element.Value);
        }
        foo.Dump();

                   break;

              case "blah":

                   break;
          }
     }