2012-06-27 14 views
1

특정 값을 가진 형제의 다음 요소 가져 오기 :Linq는 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 값을 가져와야합니다.

이 작업을 수행하는 방법을 잘 모릅니다.

감사합니다.

답변

2

당신은 ...

이 하나가 트릭을해야하는 XML @line <year>에 오타가 있지만, 몇 널 (null) 검사는 물론, 더 나은 것입니다. 그런데

, 컬러 (문이) 대신 노드의 속성이 있다면, 그것은 더 악화되지 않을 것 ...

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

감사 라파엘, 내가 오타를 수정하고 새로운 내용을 추가했습니다. 사용자 정의 노드에는 실제로 부모 노드가 있습니다. 어떻게 통합 할 생각인가? –

+0

@ChrisConway 새로운 요구 사항으로 편집되었습니다. –

+0

굉장해! 잘 했어. 감사합니다! –