user3147928
user3147928

Reputation: 41

Parsing xml with two identically-named elements

I try to parse this XML weather info into my application.

<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>

I use the following C# to parse it:

XElement XmlSneeuw = XElement.Parse(e.Result);

//current
listBoxVandaag.ItemsSource
    = from weather in XmlSneeuw.Descendants("weather")
      select new AlgemeneInformatie
      {
          Chance_of_Snow = weather.Element("chanceofsnow").Value,
          Total_Snowfall = weather.Element("totalSnowfall_cm").Value,
      };

//Current
listBoxVandaagTop.ItemsSource
    = from weather1 in XmlSneeuw.Descendants("top") 
      select new AlgemeneInformatieTop
      {
          Actueel_Top_maxtempC = weather1.Element("maxtempC").Value,
          Actueel_Top_mintempC = weather1.Element("mintempC").Value,
      };

But now there are 2 TOP elements in my xml so this wont work. what is the best way to do this? and is this the right method to parse this kind of information?

I used this site as a reference: http://developer.nokia.com/Community/Wiki/Weather_Online_app_for_Windows_Phone

Upvotes: 3

Views: 90

Answers (2)

Damith
Damith

Reputation: 63065

you can use .Elements("top") as below, that limit the sub level elements with same name

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

Upvotes: 1

xenolightning
xenolightning

Reputation: 4230

I would suggest querying the XML using LINQ and XPath, example here

//...
var topElement = XmlSneeuw.XPathSelectElement("./weather/top")
//Create your min/max object
//...

Upvotes: 4

Related Questions