2

I get this error "Object reference not set to an instance of object error" when I execute this piece of code

xe.Element("Product") // Select the Product desc="household" element  
.Elements() 
.Select(element => 
new { Name=(string) element.Attribute("desc"),                           
Count=element.Elements().Count() });

What could be the reason?

4 Answers 4

5

Try breaking it apart.

var e = xe.Element("Product");
var elements = e.Elements();
elelements.Select(element =>...

etc.. Find the smallest unit of code that causes the error. That will help isolate things. Also, use the debugger watch windows. Look for nulls.

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

Comments

0

All these could return null:

xe.Element("Product") 

xe.Element("Product") 
.Elements() 

Comments

0

One of the references you're using is null. Verify that xe is non-null, and that there is a Product tag, that has elements. Also, if the selected tag doesn't have any child elements, then the setting of the Count property on the anonymous type could generate this error, as well.

If nothing else, you can try to split this into multiple lines to see which line throws the exception. That should help you to narrow down the problem.

Comments

0

Have you checked to verify that xe is not "null". That is the most likely cause of your problem.

Comments

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.