I am trying to parse a local XML file that I have in my solution. I am using the following code:
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;
It works for the first element in drinkList, then returns a System.NullReferenceException.
What am i doing wrong?
NullReferenceException
is most likely caused by incomplete structure of some of Drink
nodes. You can avoid it when you cast element to string
, as opposed to fetching content via .Value
property:
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")
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.