简体   繁体   English

如何使用XML至LINQ将数据从C#中的xml文件添加到字典中

[英]How to add data to a dictonary from xml file in c# using XML to LINQ

The xml file is having the following structure xml文件具有以下结构

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

and the dictonary 和字典式

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

i need to read the attribute value of "value" from the file and add the same to the dictonary as value and index as key 我需要从文件中读取“值”的属性值,并将其作为值和索引作为键添加到字典中

like 喜欢

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

for this i'm using the XML to LINQ query as 为此,我正在使用XML到LINQ查询

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

wat i have to use in the place of "????" 我必须使用wat代替“ ????” in the query 在查询中

please give a solution to do this 请为此提供解决方案

You're immediate problem is that you can't have two entries in the dictionary with the same keys, I'm assuming you'll want some sort of identifier.... 您的直接问题是字典中不能有两个具有相同键的条目,我假设您需要某种标识符。

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

But then, if its just a sequential collection, why not just use a list: 但是,如果它只是一个顺序集合,为什么不只使用一个列表:

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

Edit: I didn't know about the element index part, good call peoples! 编辑:我不知道元素索引部分,大家好!

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

If you need access to the index of an element in a sequence, you can use the overload of Enumerable.Select that takes a Func<TSource, int, TResult> . 如果需要访问序列中元素的索引,则可以使用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);

I assume you don't actually want them all to have the same key, but rather an index value indicating their position in the original set: 我假设您实际上并不希望它们都具有相同的键,而是需要一个索引值来指示它们在原始集中的位置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM