测试是否存在xelement

时间:2009-03-06 15:57:43

标签: xml vb.net linq-to-xml

我正在阅读一个如下所示的XML文件:

<?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>

这是从eBay网络服务返回的样本数据,所以不要在结构上烧烤。

无论如何,我正在使用这样的代码来读取xml并将所有Vehicle放在List(of Vehicle)对象中,如下所示:

   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}

然后将生成的List(Of Vehicle)绑定到呈现数据的ASP.NET ListView控件。一切顺利如果所有需要的节点都存在。例如,“里程”节点是有条件的,有时不存在。每当节点不存在时,我都会收到“Sequence contains no elements”错误。

我已经尝试了所有我知道的事情来使事情正常运转。有没有办法测试XElement是否存在?

1 个答案:

答案 0 :(得分:2)

这取决于节点不存在时您想要做什么。例如,如果Nothing不可接受,那么您可以从.Single切换到.SingleOrDefault。在空序列的情况下,后者将返回Nothing,并且不会抛出异常。

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}