I'm reading an XML file that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<VehicleList>
<Vehicle>
<Item>
<Name>F-150</Name>
<Maker>Ford</Maker>
<Color>Black</Color>
<Price>30000</Price>
</Item>
<ItemSpecific>
<NameValueList>
<Name>Mileage</Name>
<Value>56000</Value>
</NameValueList>
<NameValueList>
<Name>Year</Name>
<Value>2003</Value>
</NameValueList>
</ItemSpecific>
</Vehicle>
<!-- more Vehicle nodes here -->
</Vehicles>
This is sample data returned from the eBay Web Service so don't grill me on the structure.
Anyway, I'm using code like this to read the xml and place all Vehicles in a List(of Vehicle) object, like so:
Dim vehicles = From v in doc...<Vehicle> _
Let mile = (From x In v.<ItemSpecific>.<NameValueList> Where x.<Name>.Value = "Mileage" Select x.<Value>.Value).Single _
Let year = (From z In v.<ItemSpecific>.<NameValueList> Where z.<Name>.Value = "Year" Select z.<Value>.Value).Single _
Select New Vehicle With {.Name = v.<Item>.<Name>.Value, .Maker = v.<Item>.<Maker>.Value, .Color = v.<Item>.<Color>.Value, .Mileage = mile, .Year = year}
The resulting List(Of Vehicle)
is then bound to an ASP.NET ListView
control where the data is rendered. All goes well if all the desired nodes are present. For example, the Mileage node is conditional and is absent sometimes. Whenever the node isn't present I get a "Sequence contains no elements
" error.
I've tried everything I know to get things working properly. Is there a way to test if an XElement exists?