views:

711

answers:

1

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?

+1  A: 

It depends on what you want to do when the node is not there. For instance if Nothing is acceptable then you can switch from .Single to .SingleOrDefault. The latter will return Nothing in the case of an empty sequence and will not throw an exception.

Dim vehicles = From v in doc...<Vehicle> _
               Let mile = (From x In v.<ItemSpecific>.<NameValueList> Where x.<Name>.Value = "Mileage" Select x.<Value>.Value).SingleOrDefault _
               Let year = (From z In v.<ItemSpecific>.<NameValueList> Where z.<Name>.Value = "Year" Select z.<Value>.Value).SingleOrDefault _
               Select New Vehicle With {.Name = v.<Item>.<Name>.Value, .Maker = v.<Item>.<Maker>.Value, .Color = v.<Item>.<Color>.Value, .Mileage = mile, .Year = year}
JaredPar
Whoa! That was fast. And it works like a champ. I tell ya, if I had your hands, I'd cut mine off! Thanks! :-)
Dude-Dastic
@Dude, http://upload.wikimedia.org/wikipedia/en/thumb/a/aa/Futurama_ep72.jpg/200px-Futurama_ep72.jpg
JaredPar
lol! Leave it to Fry to beat me to it! Cheers!
Dude-Dastic