Linq to XML-获取具有特定值的兄弟元素的下一个元素
我有一个类似于以下内容的xml结构:Linq to XML-获取具有特定值的兄弟元素的下一个元素,linq,linq-to-xml,Linq,Linq To Xml,我有一个类似于以下内容的xml结构: <cars> <car> <make>Ford</make> <model>F-150</model> <year>2011</year> <customs> <customAttribute>Color</customAttribute> <customValu
<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>
如何填充颜色和门字段?我需要获取相应customValue节点的customAttribute值
不太清楚如何做到这一点
非常感谢 您的xml@line
中有一个输入错误,但是
这一个应该可以做到,很少的空检查当然会更好
顺便说一句,如果颜色(和门)是属性而不是节点,情况不会更糟
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();
谢谢Raphaël,我已经修正了打字错误并添加了新的细节。自定义节点实际上有一个父节点。有没有关于如何整合的想法?@ChrisConway根据您的新需求进行了编辑。
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();