2010-10-28 73 views
1

我有下面的C#代碼,我不知道爲什麼它不工作(我得到一個NullReferenceException錯誤)。如果我將食譜定義爲新的List(),那麼所有東西都開始工作了。ToList裏面的C#XML ToList

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; 
     } 

感謝您的幫助!

+0

什麼行代碼給你空引用異常? – 2010-10-28 16:33:34

+0

爲什麼你反覆將'VegetablesList'分配給'ItemsSource'? – AnthonyWJones 2010-10-28 16:35:47

+0

順便說一句,使用'名稱=(字符串)recipes.Element(「名稱」)'它會讓你編碼更容易閱讀。 – AnthonyWJones 2010-10-28 16:39:07

回答

0

我的猜測是,element.Element("recipes")返回null,這意味着該迭代不存在recipes元素。

+0

謝謝!通過改變element.Element(「recipes」)修復。Elements()to vegetables.Element(「recipes」)。Elements() – 2010-10-28 16:51:24

+0

不客氣。 – 2010-10-28 16:52:10

+0

Null是Linq to XML中的一個痛處。我一直在爲此而戰。 – 2010-10-28 16:56:13