你调用的对象是空的。 试图将XML放入List中
我必须遵循XML代码,我想将其转换为带有键和值的List:
getClient 10292
我的C#代码是这样的:
XElement aValues = XElement.Parse(sMessage); List<KeyValuePair> oValues = aValues.Element("root").Elements().Select(e => new KeyValuePair(e.Name.ToString(), e.Value)).ToList();
sMessage是XML字符串。
现在我收到以下错误,我无法弄清楚原因:“对象引用未设置为对象的实例。”
有人可以帮帮我吗? 提前致谢!
"root"
是你的aValues
元素。 因此, aValue
子元素中没有"root"
元素,而aValues.Element("root")
null
。
正确的查询:
aValue.Elements() .Select(e => new KeyValuePair(e.Name.LocalName, e.Value)) .ToList();
而不是Element("root").Elements()
只使用aValues.Descendants()
。在这种情况下, aValues
已经是你的根元素。你在root中寻找root
,所以它返回null
。 顺便说一句,您可以使用Dictionary
而不是List
var oValues = aValues.Descendants() .ToDictionary(x => x.Name, x => (object) x);