1

我有一个类似于这样的 xml 结构:

<cars>
  <car>
    <make>Ford</make>
    <model>F-150</model>
    <year>2011</year>
    <customs>
      <customAttribute>Color</customAttribute>
      <customValue>Black</customValue>
      <customAttribute>Doors</customAttribute>
      <customValue>2</customValue>
    </customs>
  </car>
</cars>

我想以如下所示的方法返回汽车列表:

return (from car in cars.Descendants("car")
       select new Car {
           Make = car.Element("make").Value,
           Model = car.Element("model").Value,
           Year = car.Element("year").Value
           Color = ?????,
           Doors = ?????
       });

如何填充颜色和门字段?我需要为适当的 customValue 节点获取 customAttribute 值。

不太清楚如何做到这一点。

非常感谢!

4

1 回答 1

2

您的 xml @line 中有错字<year>,但是...

这个应该可以解决问题,当然,很少有空检查会更好。

顺便说一句,如果颜色(和门)是属性而不是节点,那也不会更糟……

var result = cars.Descendants("car")
              .Select(car => new Car
                     {
                        Make = car.Element("make").Value,
                        Model = car.Element("model").Value,
                        Year = car.Element("year").Value,
                        Color = (car.Element("customs").Elements("customAttribute").First(m => m.Value == "Color").NextNode as XElement).Value,
                        Doors = (car.Element("customs").Elements("customAttribute").First(m => m.Value == "Doors").NextNode as XElement).Value
                     })
              .ToList();
于 2012-06-27T20:02:21.517 回答