【问题标题】:How to add data to a dictonary from xml file in c# using XML to LINQ如何使用 XML to LINQ 在 c# 中将数据从 xml 文件添加到字典
【发布时间】:2010-07-01 20:20:02
【问题描述】:

xml 文件具有以下结构

<Root>
    <Child value="A"/>
    <Child value="B"/>
    <Child value="C"/>
    <Child value="D"/>
     <Child value="E"/>
</Root>

和字典

     Dictionary<int, string> dict = new Dictionary<int, string>();

我需要从文件中读取“value”的属性值,并将其添加到字典中作为值和索引作为键

喜欢

    dict[1]="A"
    dict[2]="B"
    dict[3]="C"
    dict[4]="D"
    dict[5]="E"

为此,我使用 XML to LINQ 查询

    dict = XDOC.Load(Application.StartupPath + "\\Test.xml"). 
                Descendants("Child").ToDictionary("????", x => x.Attribute("Value").Value);

我必须用 wat 代替“????”在查询中

请给出解决方案

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:
    dict = XDOC
        .Load(Application.StartupPath + "\\Test.xml")
        .Descendants("Child")
        .Select((x,i) => new {data=x, index=i})
        .ToDictionary(x => x.index, x => x.data.Attribute("Value").Value);
    

    【讨论】:

      【解决方案2】:

      您的直接问题是字典中不能有两个具有相同键的条目,我假设您需要某种标识符....

      int i = 0;
      var dic = XDOC.Load(...)
        .Root
        .Descendants("Child")
        .ToDictionary(el => (i++), el => el.Attribute("value").Value);
      

      但是,如果它只是一个顺序集合,为什么不使用列表:

      var list = XDOC.Load(...)
        .Root
        .Descendants("Child")
        .Select(el => el.Attribute("value").Value)
        .ToList();
      

      编辑:我不知道元素索引部分,好叫人!

      【讨论】:

      • Select 重载是必经之路。不太热衷于有副作用的 Linq。列表的想法非常精明:)
      【解决方案3】:

      我假设您实际上并不希望它们都具有相同的键,而是指示它们在原始集合中的位置的索引值:

              var dict = xDoc.Descendants("Child")
                  .Select((xe, i) => new { Index = i, Element = xe })
                  .ToDictionary(a => a.Index, a => a.Element.Attribute("value").Value);
      

      【讨论】:

        【解决方案4】:

        如果您需要访问序列中元素的索引,您可以使用Enumerable.Select 的重载,它采用Func&lt;TSource, int, TResult&gt;

        dict = XDOC.Load(Application.StartupPath + "\\Test.xml")
            .Descendants("Child")
            .Select((element, index) => 
                new { index, value = element.Attribute("Value").Value })
            .ToDictionary(x => x.index, x => x.value);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多