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!
"root"
is youraValues
element. So, there is no"root"
elements in children ofaValue
, andaValues.Element("root")
gives younull
.Correct query:
Instead of
Element("root").Elements()
just useaValues.Descendants()
.In this caseaValues
is already your root element.You are looking forroot
inside ofroot
so it returnsnull
. BTW, you can use aDictionary
instead ofList<KeyValuePair<string, object>>