代码之家  ›  专栏  ›  技术社区  ›  Thorin Oakenshield

如何使用xml to LINQ将数据从c中的xml文件添加到听写中

  •  0
  • Thorin Oakenshield  · 技术社区  · 14 年前

    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”的属性值,并将其添加到dictional as value和index as key中

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

    请给出解决方法

    4 回复  |  直到 14 年前
        1
  •  1
  •   spender    14 年前
    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
  •  1
  •   Matthew Abbott    14 年前

    你眼前的问题是,字典里不能有两个相同键的条目,我假设你需要某种标识符。。。。

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

    编辑:我不知道的元素索引部分,很好的呼吁人民!

        3
  •  0
  •   Toby    14 年前

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

            var dict = xDoc.Descendants("Child")
                .Select((xe, i) => new { Index = i, Element = xe })
                .ToDictionary(a => a.Index, a => a.Element.Attribute("value").Value);
    
        4
  •  0
  •   Quartermeister    14 年前

    如果需要访问序列中元素的索引,可以使用 Enumerable.Select 那得花点时间 Func<TSource, int, TResult>

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