I wrote this code to check if a XmlNode has a value, but when I run it crash always on the !=null. It is strange because this solution is well known.
private static void TraverseNodes(XmlNodeList nodes)
{
foreach (XmlNode node in nodes)
{
if (!node.HasChildNodes)
{
Console.WriteLine(node.Name + " " + node.Attributes["id"].Value);
}
if (node.Attributes["SplitCombinationOperator"].Value != null)
{
Console.WriteLine(node.Name + " " + node.Attributes["SplitCombinationOperator"].Value);
}
else
{
Console.WriteLine(node.Name);
}
TraverseNodes(node.ChildNodes);
}
}
The error is the following: Object reference not set to an instance of an object.
You only need to check whether the attribute indexer itself returns null:
if (node.Attributes["SplitCombinationOperator"] != null)
Currently, that's returning null, and you're dereferencing it for the Value
property - hence the exception. Note that you're also assuming there'd an id
property, which may not be a good idea.
(You don't need to check whether Value
itself is null - if the attribute exists, the value is non-null. Even if it's empty, you'll get an empty string rather than a null reference.)
See more on this question at Stackoverflow