Linq to XML - 获取具有特定值的兄弟的下一个元素

时间:2012-06-27 19:46:33

标签: linq linq-to-xml

我有一个与此类似的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值。

不太确定如何做到这一点。

非常感谢!

1 个答案:

答案 0 :(得分:2)

您的xml @line <year>中有拼写错误,但是......

这个应该可以做到这一点,当然,几个空检查会更好。

顺便说一句,如果Color(和Doors)是属性而不是Nodes,那就不会更糟......

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();