Similar questions have been asked before, but I cannot find the answer to the problem I have.
I want to use linq xml functions to convert my config.xml settings into dictionary, but always got Possible System.NullReferenceException. So, I need to check whether the attribute and its values exist.
What’s the syntax to do that?
<?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>
my lambda code:
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);
Use
Descendants("add")instead ofDescendants("Services")