C# 使用两个同名元素解析xml

C# 使用两个同名元素解析xml,c#,xml,xml-parsing,C#,Xml,Xml Parsing,我尝试将这个XML天气信息解析到我的应用程序中 <weather> <date>2014-01-03 </date> <chanceofsnow>0</chanceofsnow> <totalSnowfall_cm>0.0</totalSnowfall_cm> <top> <maxtempC>-3</maxtempC> <maxtemp

我尝试将这个XML天气信息解析到我的应用程序中

<weather>
  <date>2014-01-03
  </date>
  <chanceofsnow>0</chanceofsnow>
  <totalSnowfall_cm>0.0</totalSnowfall_cm>
  <top>
    <maxtempC>-3</maxtempC>
    <maxtempF>27</maxtempF>
    <mintempC>-5</mintempC>
    <mintempF>24</mintempF>
  </top>
  <hourly>
    <time>100</time>
    <top>
      <tempC>-6</tempC>
      <tempF>20</tempF>
      <windspeedMiles>8</windspeedMiles>
      <windspeedKmph>13</windspeedKmph>
      <winddirDegree>213</winddirDegree>
      <winddir16Point>SSW</winddir16Point>
      <weatherCode>113</weatherCode>
      <weatherIconUrl><![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png]]>        </weatherIconUrl>
      <weatherDesc><![CDATA[Clear]]></weatherDesc>
    </top>
  </hourly>
</weather>
但是现在我的xml中有两个顶级元素,所以这不起作用。最好的方法是什么?这是解析此类信息的正确方法吗

我将此网站用作参考:

我建议使用LINQ和XPath查询XML,例如


您可以使用如下所示的
.Elements(“top”)
,以限制具有相同名称的子级别元素

listBoxVandaagTop.ItemsSource = XmlSneeuw.Elements("top").Select( weather1=> new AlgemeneInformatieTop
      {
          Actueel_Top_maxtempC = weather1.Element("maxtempC").Value,
          Actueel_Top_mintempC = weather1.Element("mintempC").Value,
      });

正如Xenolightning所建议的,您可以使用XPath,还可以查看此参考以了解更多信息:
//...
var topElement = XmlSneeuw.XPathSelectElement("./weather/top")
//Create your min/max object
//...
listBoxVandaagTop.ItemsSource = XmlSneeuw.Elements("top").Select( weather1=> new AlgemeneInformatieTop
      {
          Actueel_Top_maxtempC = weather1.Element("maxtempC").Value,
          Actueel_Top_mintempC = weather1.Element("mintempC").Value,
      });