Second iteration in XML reading with Linq



I have a webservice running in C#, which communicates to an external party with XML-files. All works great, but now I need to scan a XML-file which has 2 elements that I need to iterate over. The XML has the same layout as the one below.



<Order>
<OrderLine>
<OrderID>5</OrderID>
<Description>OrderDescription</Description>
<Value>150</Value>
<Option>
<OptionID>15</OptionID>
<OptionDescription>OptionDescription</OptionDescription>
</Option>
<Option>
<OptionID>16</OptionID>
<OptionDescription>Another Option</OptionDescription>
</Option>
<OrderLine>
<OrderLine>
<OrderID>5</OrderID>
<Description>OrderDescription</Description>
<Value>150</Value>
<Option>
<OptionID>5</OptionID>
<OptionDescription>OptionDescription</OptionDescription>
</Option>
<OrderLine>
</Order>


In the webservice I iterate over every OrderLine element within the Order parent. Works as it should.


The problem however lays in the Option-elements within the OrderLine. The amount of Option-elements is not static. Per OrderLine it can vary. So I though I'd use the same method as I use for the OrderLines. However I get an expection when I do this.



Object reference not set to an instance of an object


I narrowed the exception down to the problem. And it lays in this line.



Options = (from option in lines.Elements("Option")
where option.HasElements
select new Option() {
OptionId = option.Element("OptionID").Value,
Description = option.Element("OptionDescription").Value
}).ToList()


Options is a IEnumerable with Option as its class. The Option class has 2 variables, OptionID and Description.

Any thoughts on how to correctly reference the object?


No comments:

Post a Comment