I am using linq to xml to extract a list of Station data from a xmlstring xmlData. The xmldata looks like this:
<Observations>
<Observation>
<Station>ADELONG POST OFFICE</Station>
<DateTime>2010-09-02T00:00:00</DateTime>
<Temperature>19.212989033764689</Temperature>
</Observation>
<Observation>
<Station>ADELONG POST OFFICE</Station>
<DateTime>2010-09-01T00:00:00</DateTime>
<Temperature>28.529448969536205</Temperature>
</Observation>
<Observation>
<Station>ALBURY AIRPORT</Station>
<DateTime>2010-09-01T00:00:00</DateTime>
<Temperature>34.687027630716109</Temperature>
</Observation>
<Observation>
<Station>ALBURY AIRPORT AWS</Station>
<DateTime>2010-09-01T00:00:00</DateTime>
<Temperature>28.131385570453197</Temperature>
</Observation>
</Observations>
I am trying to query this xmlstring to extract the name of the station for only the most recent datetime. I also would like to retrieve the most recent temperature.
I have defined a station class:
public class Station
{
public string Name { get; set; }
public DateTime MostRecentDate { get; set; }
public decimal LastTemperature { get; set; }
}
How can I list the most recent temperature+datetime+name for each station ?
I am running this in a c# console application (complete code):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace weatherxml
{
class Program
{
static void Main(string[] args)
{
string xmlData = @"<Observations><Observation><Station>ADELONG POST OFFICE</Station><DateTime>2010-09-02T00:00:00</DateTime><Temperature>19.212989033764689</Temperature></Observation><Observation><Station>ADELONG POST OFFICE</Station><DateTime>2010-09-01T00:00:00</DateTime><Temperature>28.529448969536205</Temperature></Observation><Observation><Station>ALBURY AIRPORT</Station><DateTime>2010-09-01T00:00:00</DateTime><Temperature>34.687027630716109</Temperature></Observation><Observation><Station>ALBURY AIRPORT AWS</Station><DateTime>2010-09-01T00:00:00</DateTime><Temperature>28.131385570453197</Temperature></Observation></Observations>";
XDocument weatherData = XDocument.Parse(xmlData);
var stations = from item in weatherData.Descendants("Observation")
select new Station
{
Name = item.Element("Station").Value,
MostRecentDate = DateTime.Parse(item.Element("DateTime").Value),
LastTemperature = Decimal.Parse(item.Element("Temperature").Value)
};
var st = stations;
foreach (var s in st)
{
Console.WriteLine(s.Name);
}
Console.ReadLine();
}
}
public class Station
{
public string Name { get; set; }
public DateTime MostRecentDate { get; set; }
public decimal LastTemperature { get; set; }
}
}