user840718
user840718

Reputation: 1611

C# check XmlNode value attribute

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.

Upvotes: 0

Views: 879

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502206

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

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26876

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.

Upvotes: 1

Related Questions