2011-08-20 3 views
1

저는 C#과 XML을 처음 접했고 MediaPortal을위한 작은 날씨 플러그인을 개발하려고합니다. Visual C# 2010 Express에서 Linq를 사용하여 XML을 구문 분석하려고하는데로드 블록이 발생했습니다. 여기 도움이 필요하십니까 Linq로 XML 파싱

<forecast> 
    <period textForecastName="Monday">Monday</period> 
    <textSummary>Sunny. Low 15. High 26.</textSummary> 
<temperatures> 
    <textSummary>Low 15. High 26.</textSummary> 
    <temperature unitType="metric" units="C" class="high">26</temperature> 
    <temperature unitType="metric" units="C" class="low">15</temperature> 
    </temperatures> 
</forecast> 

지금까지 내 작업 코드입니다 : 여기

내가 구문 분석을 시도하고있는 XML의 하위 집합입니다

XDocument loaded = XDocument.Parse(strInputXML); 
var forecast = from x in loaded.Descendants("forecast") 
select new 
{ 
    textSummary = x.Descendants("textSummary").First().Value, 
    Period = x.Descendants("period").First().Value, 
    Temperatures = x.Descendants("temperatures"), 
    Temperature = x.Descendants("temperature"), 
    //code to extract high e.g. High = x.Descendants(...class="high"???), 
    //code to extract low e.g. High = x.Descendants(...class="low"???) 
}; 

내 코드가 내 자리 코멘트까지 작동하지만 Linq를 사용하여 XML에서 high (26)와 low (15)를 추출하는 방법을 알아낼 수 없습니다. 나는 이것을 "온도"에서 수동으로 파싱 할 수 있었지만 XML 구조에 대해 좀 더 배울 수 있기를 희망합니다.

도움 주셔서 감사합니다. 더그

당신이 뭔가 처럼 원하는 것 같습니다

답변

0

:

High = (int)x.Descendants("temperature") 
      .Single(e => (string)e.Attribute("class") == "high") 

이 (없음 또는 여러가없는 경우가 발생합니다) 값 high와 속성 class을 갖는 temperature 자손을 발견, 그 값을 정수로 변환합니다.

그러나 완전히 명확하지 않습니다.

forecast 요소는 복수temperatures 요소를 가질 수 있습니까? temperatures 요소에 class == "high"을 갖는 복수 temperature 요소가있을 수 있습니까? 다른 unitTypes을 어떻게 처리하고 싶습니까?

Highs = x.Descendants("temperature") 
     .Where(e => (string)e.Attribute("class") == "high") 
+0

감사 :

은 당신이 뭔가를 할 수있는 요소를 얻으려면. 게시물의 마지막 줄을 사용하기 위해 높음 및 낮음 요소를 가져와야했습니다. 이제 나는 배워야 겠어. 어디서. (나는이 물건에 정말로 새롭다!) – Doug