tags:

views:

127

answers:

2

Hi I have got this code:

XDocument xdoc = XDocument.Load(URI);
            XElement root = xdoc.Element("forecast");
            //get the values into objects
            forecast = from fc in root.Descendants("simpleforecast").Elements("forecastday")
                       select new DayForcast
                       {
                           Date = new DateTime(int.Parse(fc.Element("date").Element("year").Value),
                               int.Parse(fc.Element("date").Element("month").Value),
                               int.Parse(fc.Element("date").Element("day").Value)),
                           Condition = fc.Element("conditions").Value,
                           Max = double.Parse(fc.Element("high").Element("celsius").Value),
                           Min = double.Parse(fc.Element("low").Element("celsius").Value),
                           Icon = fc.Element("icon").Value,
                           SkyIcon = fc.Element("skyicon").Value
                       };

Although this does what I want, I want to know if there is a better way to do the fc.Element("low").Element("celsius").Value parts, so that the Element().Element() is one Element().

Here is a sample of the XML:

<?xml version="1.0" ?> 
<forecast>
<termsofservice link="http://www.wunderground.com/members/tos.asp#api" /> 
<txt_forecast>
  <date /> 
  <number /> 
</txt_forecast>
<simpleforecast>
  <forecastday>
  <period>1</period> 
  <date>
       <day>7</day> 
       <month>7</month> 
       <year>2009</year> 
       <yday>187</yday> 
       <hour>22</hour> 
  </date>
  <high>
      <fahrenheit>63</fahrenheit> 
      <celsius>17</celsius> 
  </high>
  <low>
      <fahrenheit>54</fahrenheit> 
      <celsius>12</celsius> 
  </low>
<conditions>Thunderstorm</conditions> 
<icon>tstorms</icon> 
<skyicon>cloudy</skyicon>

Thanks

+1  A: 

You should consider using serialization to deserialize an DayForcast object from this xml fragment.

Oliver Hanappi
I think the OP want to know the LINQ way of doing it.
SharePoint Newbie
Hi, thanks for the answer. The result is from a RSS feed which I cannot get to serialise...I am VERY unfamiliar with serialisation as well.
A: 

Hi,

You could use XElement.XPathSelectElements("xpathExpression") if you want to do it more concisely, but there's nothing wrong with what you've done.

Your code is more verbose and easier to read.

SharePoint Newbie
Thanks for your answer!