Make a temperature forecast in C#

[forecast]

The example Get weather forecast data in C# explains how to read weather forecast data from OpenWeatherMap. This example uses that data to list the forecast’s temperatures.


The forecast data has (in part) the following structure.

<weatherdata>
  ...
  <forecast>
    <time from="2016-05-18T12:00:00" to="2016-05-18T15:00:00">
      <symbol ... >...</symbol>
      <precipitation ...>...</precipitation>
      <windDirection ...>...</windDirection>
      <windSpeed ...>...</windSpeed>
      <temperature unit="imperial" value="50.11"
          min="50.11" max="52.58">
      </temperature>
      <pressure ...>...</pressure>
      <humidity ...>...</humidity>
      <clouds ...>...</clouds>
    </time>
    <time...>
    ...
    </time>
    ... time repeats 40 times ...

  </forecast>
</weatherdata>

To display the temperatures, the program loops through the time elements. For each of those, it finds the element’s temperature child and displays its value attribute. The program uses the following ListTemperatures method to do that.

// List the temperatures.
private void ListTemperatures(XmlDocument xml_doc)
{
    lvwTemps.Items.Clear();

    // Loop throuh the time entries.
    string last_day = "";
    foreach (XmlNode time_node in xml_doc.SelectNodes("//time"))
    {
        // Get the start date and time.
        XmlAttribute time_attr = time_node.Attributes["from"];
        DateTime start_time = DateTime.Parse(time_attr.Value);

        // Convert from UTC to local time.
        start_time = start_time.ToLocalTime();

        // Add 90 minutes to get to the middle of the interval.
        start_time += new TimeSpan(1, 30, 0);

        // Get the temperature node.
        XmlNode temp_node =
            time_node.SelectSingleNode("temperature");
        XmlAttribute temp_attr = temp_node.Attributes["value"];
        float temp = 0;
        if (temp_attr != null)
            temp = float.Parse(temp_attr.Value.ToString());

        ListViewItem item;
        if (start_time.DayOfWeek.ToString() == last_day)
            item = lvwTemps.Items.Add("");
        else
        {
            last_day = start_time.DayOfWeek.ToString();
            item = lvwTemps.Items.Add(last_day);
        }
        item.SubItems.Add(start_time.ToShortTimeString());
        item.SubItems.Add(temp.ToString("0.00"));
    }
}

The method first clears the form’s ListView control. It then uses the XmlDocument object’s SelectNodes method to find the document’s time elements and it looks through them. Each time element represents a three-hour forecast.

For each time element, the method gets the element’s from attribute to see when the time interval starts. It parses the start time, converts it from UTC tome to local time, and adds 90 minutes to get the middle of the time interval.

Next the code uses the time node’s SelectSingleNode method to get that node’s temperature child. The method finds that element’s value attribute and parses it to get the temperature.

The code then gets the start time’s day of the week. If it is the same day of the week as the previous time element, the program adds a blank entry to the ListView control. If this is a new day of the week, the code adds it to the ListView.

The program then adds the start time and the temperature as sub-items so they appear in separate ListView columns.

You can use a similar technique to list other parts of the forecast. For example, you can list the predicted wind or amount of rain. Download the example to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in internet, interoperability, web, XML and tagged , , , , , , , , , , , , . Bookmark the permalink.

5 Responses to Make a temperature forecast in C#

  1. Emmanuel says:

    Which one of your books contains exactly these codes from: http://csharphelper.com/blog/2016/05/make-temperature-forecast-c/

    • RodStephens says:

      Many (most?) of the posts on this site contain code that isn’t in any of my books. “Visual Basic .NET and XML” talks about searching XML data and I think a couple of others talk a bit about using XmlDocument objects, but none cover exactly this.

  2. Decraie says:

    Question: how would you try to find e.g. the node temperature if it were also present in another word please? Like:

    wanting ALL temperature present?

    • RodStephens says:

      I don’t think I understand what you want. If you want to load a bigger data set and then query it, you might look at XQuery and XSLT. They let you query XML data. For example, if you had lots of data you could search it for data about a particular city or data from all cities for Monday.

      Unfortunately XQuery and XSLT are big topics so you might want to get a book. (My book “Visual Basic .NET and XML” covers this, but it’s in Visual Basic and a bit older. (Although not much has changed since then so you might be able to get a used copy cheap and still learn what you need.))

Leave a Reply

Your email address will not be published. Required fields are marked *