views:

35

answers:

1

I have the following C# code and I have no idea why it's not working (I'm getting a NullReferenceException error). If I define Recipe as new List() everything starts working OK.

foreach (XElement element in document.Descendants("vegetables"))
        {
            VegetablesList = (
                from vegetables in element.Elements()
                select new FoodItem()
                {
                    Name = (vegetables.Element("name") == null) ? null : vegetables.Element("name").Value.ToString(),
                    Bcg = (vegetables.Element("bcg") == null) ? null : vegetables.Element("bcg").Value.ToString(),
                    Info = (vegetables.Element("info") == null) ? null : vegetables.Element("info").Value.ToString(),
                    Recipes = (
                        from recipes in element.Element("recipes").Elements()
                        select new Recipe()
                        {
                            Name = (recipes.Element("name") == null) ? null : recipes.Element("name").Value.ToString(),
                            Text = (recipes.Element("text") == null) ? null : recipes.Element("text").Value.ToString()
                        }
                    ).ToList()
                }
            ).ToList();
            VegetablesListBox.ItemsSource = VegetablesList;
        }

Thanks for your help!

A: 

My guess is that element.Element("recipes") returns null, which means that the recipes element does not exist for that iteration.

Pieter
Thanks! Fixed by changing element.Element("recipes").Elements() to vegetables.Element("recipes").Elements()
Philip Seyfi
You're welcome.
Pieter
Null is a pain in the ass in Linq to XML. I'm constantly fighting that.
Robert Harvey
@Robert Harvey - Isn't it great that Linq actually tells you very clearly that you're having a problem with your code though? Instead of just silently returning empty collections making your problems very very hard to debug?!?
Pieter
@Pieter: Well, I wound up writing some extension methods to short-circuit all of the nulls and return empty collections. It was just getting way too difficult to check every returned object for null before calling methods on it. Unless live objects are *always* returned, it's pretty much impossible to chain the `Elements()` and `Descendants()` methods, which is what I wanted to do.
Robert Harvey