0

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.

1
  • The SplitCombinationOperator may not exist, while your code assumes the "Value" property will be available, in any case. Commented Jul 14, 2015 at 15:36

2 Answers 2

1

You should check for null values something like this:

node.Attributes["SplitCombinationOperator"] != null &&
node.Attributes["SplitCombinationOperator"].Value != null

Otherwise you will get NullReferenceException when node.Attributes["SplitCombinationOperator"] is null while trying to access its Value property.

Sign up to request clarification or add additional context in comments.

1 Comment

Good, now I understand.
1

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.)

1 Comment

I was figuring out why it was not working, but this explanation made it very clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.