使用LINQ计算由父组合的XElements

时间:2016-08-24 08:28:48

标签: c# xml linq

考虑以下XML ...

<stock>
    <dealer>
        <dealername>Dealer 1</dealername>
        <vehicle>
            <stockID>11111</stockID>
            ...
        </vehicle>
        <vehicle>
            <stockID>22222</stockID>
            ...                
        </vehicle>
        <vehicle>
            <stockID>33333</stockID>
            ...
        </vehicle>
    </dealer>
    <dealer>
        <dealername>Dealer 2</dealername>
        <vehicle>
            <stockID>44444</stockID>
            ...
        </vehicle>
        <vehicle>
            <stockID>55555</stockID>
            ...                
        </vehicle>
    </dealer>
</stock>

我需要解析此XML并插入包含...

的db记录
Dealer Name
Count of Vehicles for that Dealer Name

...所以对于上面的例子,这将是......

DealerName    Count of Vehicles
Dealer 1      3
Dealer 2      2

我正在使用以下LINQ代码,但我似乎无法得到我需要的结果......

// count the number of vehicles by dealer name
var qry = from dealer in downloadedXml.Descendants("dealername")
          group dealer by dealer.Value
          into grp
          select new {
             DealerName = grp.Key,
             Count = grp.Select(x => x.Descendants("vehicle")).Distinct().Count()
          };

foreach (var row in qry.OrderBy(x => x.DealerName)) {
    // do db insert
}

2 个答案:

答案 0 :(得分:1)

尝试此查询:

var result = from d in doc.Descendants("dealer")
    select new
    {
        Name = d.Element("dealername").Value,
        Total = d.Descendants("vehicle").Count()
    };

答案 1 :(得分:0)

你可以这样做

XDocument doc = XDocument.Load(@"E:\test\r.xml");

var data =
   doc.Descendants("stock").Elements("dealer")
      .Select(
              a =>
                  new
                     {
                       DealerName = a.Element("dealername").Value,
                       VehiclesCount = a.Descendants("vehicle").Count()
                     });

foreach (var d in data)
{
    Console.WriteLine(d.DealerName);
    Console.WriteLine(d.VehiclesCount);
}