以前曾提出过类似的问题,但我找不到问题的答案。
我想使用linq xml函数将我的config.xml设置转换为字典,但始终得到Possible System.NullReferenceException
。所以,我需要检查属性及其值是否存在。
这样做的语法是什么?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<Services>
<add key ="key1" value ="value1"></add>
<add key ="key2" value ="value2"></add>
<add key ="key3" value ="value3"></add>
</Services>
</configuration>
我的lambda代码:
XDocument doc = XDocument.Load(configFilePath);
var d = (from name in doc.Descendants("Services") select name)
.ToDictionary(n => n.Attribute("key")
.Value, n.Attribute("value")
.Value);
答案 0 :(得分:3)
使用Descendants("add")
代替Descendants("Services")
var dict = XDocument.Load(configFilePath)
.Descendants("add")
.ToDictionary(n => n.Attribute("key").Value, n=> n.Attribute("value").Value);
var dict = XDocument.Load(configFilePath)
.Descendants("Services").First()
.Descendants("add")
.ToDictionary(n => n.Attribute("key").Value, n=> n.Attribute("value").Value);