【问题标题】:C# XML ToList inside ToListToList 中的 C# XML ToList
【发布时间】:2010-10-28 16:29:55
【问题描述】:

我有以下 C# 代码,但我不知道为什么它不起作用(我收到 NullReferenceException 错误)。如果我将 Recipe 定义为 new List() 一切都会开始正常工作。

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

感谢您的帮助!

【问题讨论】:

  • 哪行代码给了你空引用异常?
  • 为什么要反复将VegetablesList分配给ItemsSource
  • 顺便说一句,使用Name = (string)recipes.Element("name") 它会让你的代码更容易阅读。
  • 我在 new FoodItem() { ... } 上收到错误消息
  • @AnthonyWJones 我只分配蔬菜列表框。项目来源=蔬菜列表; - 有什么问题?

标签: c# xml linq linq-to-xml


【解决方案1】:

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

【讨论】:

  • 谢谢!通过将 element.Element("recipes").Elements() 更改为 vegetables.Element("recipes").Elements() 修复
  • Null 是 Linq to XML 中的一个难题。我一直在与之抗争。
  • @Robert Harvey - Linq 实际上非常清楚地告诉您您的代码有问题,这不是很好吗?而不是默默地返回空集合,让您的问题非常难以调试?!?
  • 好吧,我最终编写了一些扩展方法来短路所有空值并返回空集合。在调用方法之前检查每个返回的对象是否为 null 变得太困难了。除非总是返回活动对象,否则几乎不可能链接Elements()Descendants() 方法,这正是我想做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多