2011-08-20 77 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