Object reference not set to an instance of an object. Trying to put XML into a List

浪子不回头ぞ 提交于 2019-12-20 04:16:58

问题


I have to following XML code witch I like to convert into a List with keys and values:

<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<root>
<command>getClient</command>
<id>10292</id>
</root>

My C# code is like this:

XElement aValues = XElement.Parse(sMessage);
List<KeyValuePair<string, object>> oValues = aValues.Element("root").Elements().Select(e => new KeyValuePair<string, object>(e.Name.ToString(), e.Value)).ToList();

sMessage is the XML string.

Now I'm getting the following error, and I can not figure out why: "Object reference not set to an instance of an object."

Can someone please help me? Thanks in advance!


回答1:


"root" is your aValues element. So, there is no "root" elements in children of aValue, and aValues.Element("root") gives you null.

Correct query:

 aValue.Elements()
       .Select(e => new KeyValuePair<string, object>(e.Name.LocalName, e.Value))
       .ToList();



回答2:


Instead of Element("root").Elements() just use aValues.Descendants().In this case aValues is already your root element.You are looking for root inside of root so it returns null. BTW, you can use a Dictionary instead of List<KeyValuePair<string, object>>

var oValues = aValues.Descendants()
            .ToDictionary(x => x.Name, x => (object) x);


来源:https://stackoverflow.com/questions/22686496/object-reference-not-set-to-an-instance-of-an-object-trying-to-put-xml-into-a-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!