2011-08-20 78 views
1

我是C#和XML的新手,並試圖爲MediaPortal開發一個小天氣插件。我試圖在Visual C#2010 Express中使用Linq解析一些XML,並且遇到了障礙。我需要一些幫助用Linq解析XML

這裏是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> 

這是到目前爲止我的工作代碼:

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中提取高(26)和低(15)。我可以從「溫度」手動解析它,但我希望我能夠了解更多關於XML結構的知識。

感謝您的任何幫助。 道格

回答

0

它看起來像你想要的東西

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

此發現只有temperature後代(如果有沒有發或多發,它會拋出),具有屬性class與價值high,然後將其值轉換爲整數。

但它不完全清楚。

Can a forecast element have multipletemperatures elements? temperatures元素是否可以有多個temperature元素class == "high"?你想如何處理不同的unitTypes

先手的元素了,你可以這樣做:

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

感謝。我只需要得到高和低的元素,所以我在你的文章中使用了最後一行代碼。現在我要了解.Where和.Attribute。 (我*真的*新東西!) – Doug