I have to following XML code witch I like to convert into a List with keys and values:
我必须遵循XML代码,我喜欢将其转换为带有键和值的列表:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<root>
<command>getClient</command>
<id>10292</id>
</root>
My C# code is like this:
我的c#代码是这样的:
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.
sMessage是XML字符串。
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!
谁能帮帮我吗?提前谢谢!
2 个解决方案
#1
3
"root"
is your aValues
element. So, there is no "root"
elements in children of aValue
, and aValues.Element("root")
gives you null
.
“root”是你的基本知识。因此,在aValue的子元素中没有“root”元素,而avaluees.element(“root”)给您null。
Correct query:
正确的查询:
aValue.Elements()
.Select(e => new KeyValuePair<string, object>(e.Name.LocalName, e.Value))
.ToList();
#2
1
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>>
元素()不是元素(“根”),而是使用avalu.()。在这种情况下,值已经是根元素了。你在根内部寻找根,这样它就返回null。另外,你可以使用字典而不是List
var oValues = aValues.Descendants()
.ToDictionary(x => x.Name, x => (object) x);
#1
3
"root"
is your aValues
element. So, there is no "root"
elements in children of aValue
, and aValues.Element("root")
gives you null
.
“root”是你的基本知识。因此,在aValue的子元素中没有“root”元素,而avaluees.element(“root”)给您null。
Correct query:
正确的查询:
aValue.Elements()
.Select(e => new KeyValuePair<string, object>(e.Name.LocalName, e.Value))
.ToList();
#2
1
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>>
元素()不是元素(“根”),而是使用avalu.()。在这种情况下,值已经是根元素了。你在根内部寻找根,这样它就返回null。另外,你可以使用字典而不是List
var oValues = aValues.Descendants()
.ToDictionary(x => x.Name, x => (object) x);