我正在尝试解析我的解决方案中的本地XML文件。 我使用以下代码:
XDocument xml = XDocument.Load("Vodka.xml");
IEnumerable<XElement> drinkList = xml.Descendants("Drink");
DrinkGroup data = new DrinkGroup();
foreach (XElement drink in drinkList)
{
data.Items.Add(new Drinks
{
name = drink.Element("Name").Value,
image = drink.Element("Image").Value,
description = drink.Element("Description").Value,
ingredients = drink.Element("Ingredients").Value,
preperation = drink.Element("Preperation").Value
});
}
return data;
它适用于drinkList中的第一个元素,然后返回一个System.NullReferenceException。
我做错了什么?
答案 0 :(得分:1)
NullReferenceException
很可能是由某些Drink
个节点的不完整结构引起的。将元素转换为string
时可以避免使用它,而不是通过.Value
属性获取内容:
foreach (XElement drink in drinkList)
{
data.Items.Add(new Drinks
{
name = (string) drink.Element("Name"),
image = (string) drink.Element("Image"),
description = (string) drink.Element("Description"),
ingredients = (string) drink.Element("Ingredients"),
preperation = (string) drink.Element("Preperation")
});
}