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 的新手,我希望有人可以帮助我解决可能是或可能不是一个简单的问题。

对于上面的 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"

是否可以在选择中执行此操作,还是我需要单独的查询?

4

1 回答 1

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
于 2012-10-19T01:39:22.903 回答