I'm trying to convert a XML file to a list. The XML file contains different products, and each product has different values, e.g.:
<product>
<id></id>
<name>Commentarii de Bello Gallico et Civili</name>
<price>449</price>
<type>Book</type>
<author>Gaius Julius Caesar</author>
<genre>Historia</genre>
<format>Inbunden</format>
</product>
<product>
<id></id>
<name>Katana Zero</name>
<price>199</price>
<type>Game</type>
<platform>PC, Switch</platform>
</product>
The problem is that some elements does not have all fields, some books can look like this for example:
<product>
<id></id>
<name>House of Leaves</name>
<price>49</price>
<type>Bok</type>
<author>Mark Z. Danielewski</author>
<genre>Romance</genre>
</product>
When I try adding these elements to the list, it works until I get an element that does not have all fields. When that happens, I get "System.NullReferenceException: 'Object reference not set to an instance of an object'."
List<Product> products= new List<Product>();
XElement xelement = XElement.Load(path);
IEnumerable<XElement> pr = xelement.Elements();
foreach (var p in pr)
{
switch (p.Element("type").Value)
{
case "Book":
temp.Add(new Book(1, int.Parse(employee.Element("price").Value),
0 ,
p.Element("name").Value,
p.Element("author").Value,
p.Element("genre").Value,
p.Element("format").Value");
break;
}
What I would like is to get a null value or "Not specified" when that happens, but I don't know how to do that in a good way. All I can think of are try catch for each variable but that seems uneccesary complicated.
How can I handle these cases in a good way?