开发者

C# + Querying XML with LINQ

开发者 https://www.devze.com 2023-01-03 06:19 出处:网络
I\'m learning to use LINQ. I have seen some videos online that have really impressed me. In an effort to learn LINQ myself, I decided to try to write a query to the NOAA web service. If you put \"http

I'm learning to use LINQ. I have seen some videos online that have really impressed me. In an effort to learn LINQ myself, I decided to try to write a query to the NOAA web service. If you put "http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdBrowserClientByDay.php?zipCodeList=20001&format=24+hourly&startDate=2010-06-10&numDays=5" in your browser's address bar, you will see some XML. I have successfully retrieved that XML in a C# program. I am loading the XML into a LINQable entity by doing the following:

string xml = QueryWeatherService();
XDocument weather = XDocument.Parse(xml);

I have a class called DailyForecast defined as follows:

public class DailyForecast
{
  public float HighTemperature { get; set; }    
  public float LowTemperature { get; set; }
  public float PrecipitationPossibility { get; set; }
  public string WeatherSummary { get; set; }
}

I'm trying write a LINQ query that adheres to the structure of my DailyForecast class. At this time, I've only gotten to this far:

var results = from day in response.Descendants("parameters") 
              select day;

Not very far I know. Because of the structure of the XML returned, I'm not sure it is possible to solely use a LINQ query. I think the only way to do this is via a loop and traverse the XML. I'm seeking someone to correct me if I'm wrong. Can someone ple开发者_Python百科ase tell me if I can get results using purely LINQ that adhere to the structure of the DailyForecast class? If so, how?

Thank you!


Since your xml may return multiple records,

var results = from day in response.Descendants("parameters") 
              select new DailyForecast()
              {
                 HighTemperature = day.Element("param name corresponding to high temp"),
              };

return result.ToList(); //or any type of collection you want to return
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号