Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用linq从xml获取键值对_C#_Linq - Fatal编程技术网

C# 使用linq从xml获取键值对

C# 使用linq从xml获取键值对,c#,linq,C#,Linq,如何使用linq从这个xml示例中提取键值对: <foo> <add key="key1" Value="val1"/> <add key="key2" Value="val2"/> <add key="key3" Value="val3"/> <foo/> 试试这个: string text = "<foo>...</foo>"; var pairs = XDocument.Parse(text)

如何使用linq从这个xml示例中提取键值对:

<foo>
<add key="key1" Value="val1"/>
<add key="key2" Value="val2"/>
<add key="key3" Value="val3"/>
<foo/>

试试这个:

string text = "<foo>...</foo>";
var pairs = XDocument.Parse(text)
                     .Descendants("add")
                     .Select(x => new { Key = x.Attribute("key").Value,
                                        Value = x.Attribute("Value").Value })
                     .ToList();
string text=“…”;
var pairs=XDocument.Parse(文本)
.后代(“添加”)
.Select(x=>new{Key=x.Attribute(“Key”).Value,
Value=x.Attribute(“Value”).Value})
.ToList();

我想你指的是属性而不是属性,元素只使用一个元素名,而不是路径(反正是AFAIK)。嗨,这不会编译。我得到:'System.Collections.Generic.IEnumerable'不包含'Select'的定义,并且没有扩展方法'Select'接受类型的第一个参数而不是ToList();我会尝试使用:.ToDictionary(item=>item.Key,item=>item.Value);就像OP的问题对我来说更明显一样。我知道这只是一个例子,但应该是:)
XDocument fooXML = new XDocument.Load("foo.xml")
var query = from a in fooXML.Element("foo").Elements("add")
            select new
            {
                key = a.Attribute("key").Value,
                val = a.Attribute("Value").Value
            };
// Then do what you want with the query...