2012-10-18 74 views
2
<PersVeh id="V0001" LocationRef="L0001" RatedDriverRef="D0001"> 
    <Manufacturer>FORD</Manufacturer> 
    <Model>TAURUS SE</Model> 
    <ModelYear>2007</ModelYear> 
    <VehBodyTypeCd>PP</VehBodyTypeCd> 
    <POLKRestraintDeviceCd>E</POLKRestraintDeviceCd> 
    <EstimatedAnnualDistance> 
    <NumUnits>011200</NumUnits> 
    </EstimatedAnnualDistance> 
    <VehIdentificationNumber>1FAFP53U37A160207</VehIdentificationNumber> 
    <VehSymbolCd>12</VehSymbolCd> 
    <VehRateGroupInfo> 
    <RateGroup>16</RateGroup> 
    <CoverageCd>COMP</CoverageCd> 
    </VehRateGroupInfo> 
    <VehRateGroupInfo> 
    <RateGroup>21</RateGroup> 
    <CoverageCd>COLL</CoverageCd> 
    </VehRateGroupInfo> 

裏面我是全新的,以LINQ和我希望有人能幫助我什麼可能會或可能不會是一個簡單的問題。如何添加一個where子句選擇查詢

對於上述XML示例我使用以下代碼:

var result = from item in doc.Descendants(n + "PersVeh") 
      where item.Attribute("id").Value == "V0001" 
      select new 
      { 
       RatedDriverRef = (string)item.Attribute("RatedDriverRef"), 
       LocationRef = (string)item.Attribute("LocationRef"), 
       ModelYear = (string)item.Element(n + "ModelYear") ?? "9999", 
       VehBodyTypeCd = (string)item.Element(n + "VehBodyTypeCd") ?? "XX", 
       POLKRestraintDeviceCd = (string)item.Element(n + "POLKRestraintDeviceCd") ?? "0", 
       EstimatedAnnualDistance = (string)item.Element(n + "EstimatedAnnualDistance").Element(n + "NumUnits") ?? "999999", 
       VehIdentificationNumber = (string)item.Element(n + "VehIdentificationNumber") ?? "VIN not found", 
       VehSymbolCd = (string)item.Element(n + "VehSymbolCd") ?? "00" 
      }; 

時遇到的問題是與VehRateGroupInfo節點。我需要根據CoverageCd提取RateGroup號碼。

換句話說,這樣的事情:

CompSymbol = item.Element(n + "VehRateGroupInfo").Element(n + "RateGroup").Value 
      where item.Element(n + "VehRateGroupInfo").Element(n + "CoverageCd").Value == "COMP" 

是否有可能做到這一點內的選擇還是我需要一個單獨的查詢?

+0

[XML LINQ?:如何使用選擇與地方]的可能重複(HTTP: //stackoverflow.com/questions/7761006/xml-linq-how-to-use-select-with-where) – bluish

回答

0

下面是與查詢語法的解決方案:

CompSymbol = (from vehRateGroup in item.Descendants(n + "VehRateGroupInfo") 
       where vehRateGroup.Element(n + "CoverageCd").Value == "COMP" 
       select vehRateGroup.Element(n + "RateGroup").Value).Single() 

下面是用方法的語法類似的解決方案:

CompSymbol = item.Descendants(n + "VehRateGroupInfo") 
       .Single(x => x.Element(n + "CoverageCd").Value == "COMP") 
       .Element(n + "RateGroup").Value