Reputation: 413
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?
Upvotes: 2
Views: 966
Reputation: 93494
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.
Upvotes: 5
Reputation: 755587
Have you checked to verify that xe is not "null". That is the most likely cause of your problem.
Upvotes: 0
Reputation: 30428
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.
Upvotes: 0
Reputation: 74320
All these could return null:
xe.Element("Product")
xe.Element("Product")
.Elements()
Upvotes: 0