XML 使用 Linq To XML 到字典
XML to Dictionary using Linq To XML
好吧,我在这个简单的事情上迷路了。
我想把这个 xml 转换成一个字典,基本上是这样的:
var xml = "<root><Hello>World</Hello><Foo>Bar</Foo></root>";
var doc = XDocument.Parse(xml);
var dic = new Dictionary<string, string>();
foreach (var elem in doc.Root.Elements())
{
dic[elem.Name.LocalName] = elem.Value;
}
但是我想用ToDictionary,所以我这样写:
var dic = doc.Root.Elements().ToDictionary<string, string>(e => e.Name.LocalName, e => e.Value);
但是编译不通过!我收到这些错误
Error 1 Instance argument: cannot convert from
'System.Collections.Generic.IEnumerable' to
'System.Collections.Generic.IEnumerable' Program.cs 65 22
Error 2 'System.Collections.Generic.IEnumerable'
does not contain a definition for 'ToDictionary' and the best
extension method overload
'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable,
System.Func,
System.Collections.Generic.IEqualityComparer)' has some invalid
arguments Program.cs 65 22 Error 3 Argument 2: cannot convert from
'lambda expression' to 'System.Func' Program.cs 65 71
Error 4 Argument 3: cannot convert from 'lambda expression' to
'System.Collections.Generic.IEqualityComparer' Program.cs 65 94
这个
var dic = doc.Root.Elements().ToDictionary<string, string>(e => e.Name.LocalName, e => e.Value);
应该是这样的:
var dic = doc.Root.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value);
您不必声明键的类型和值的类型。有关这方面的更多文档,请查看 here。
好吧,我在这个简单的事情上迷路了。 我想把这个 xml 转换成一个字典,基本上是这样的:
var xml = "<root><Hello>World</Hello><Foo>Bar</Foo></root>";
var doc = XDocument.Parse(xml);
var dic = new Dictionary<string, string>();
foreach (var elem in doc.Root.Elements())
{
dic[elem.Name.LocalName] = elem.Value;
}
但是我想用ToDictionary,所以我这样写:
var dic = doc.Root.Elements().ToDictionary<string, string>(e => e.Name.LocalName, e => e.Value);
但是编译不通过!我收到这些错误
Error 1 Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable' Program.cs 65 22
Error 2 'System.Collections.Generic.IEnumerable' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable, System.Func, System.Collections.Generic.IEqualityComparer)' has some invalid arguments Program.cs 65 22 Error 3 Argument 2: cannot convert from 'lambda expression' to 'System.Func' Program.cs 65 71
Error 4 Argument 3: cannot convert from 'lambda expression' to 'System.Collections.Generic.IEqualityComparer' Program.cs 65 94
这个
var dic = doc.Root.Elements().ToDictionary<string, string>(e => e.Name.LocalName, e => e.Value);
应该是这样的:
var dic = doc.Root.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value);
您不必声明键的类型和值的类型。有关这方面的更多文档,请查看 here。