如何从 Weather API XML 打印所有日期

Posted

技术标签:

【中文标题】如何从 Weather API XML 打印所有日期【英文标题】:How to print all dates from Weather API XML 【发布时间】:2020-08-02 10:01:23 【问题描述】:

对于任何 lq 的事情感到抱歉,我是 c# 的新手。

我正在尝试显示来自 XML WEB API 的所有日期...

我只打印了 1 个日期,我想要 5 天?

我需要在控制台应用程序中显示 5 天的所有数据,就像我发布一个日期一样。

我应该用什么,有人可以帮我吗?

替换文本,因为堆栈不允许我发布,主要是代码。替换文本,因为堆栈不允许我发布,主要是代码。替换文本,因为堆栈不允许我发布,主要是代码.replacing 文本,因为堆栈不允许我发布,主要是 code.replacing 文本,因为堆栈不允许我发布,主要是 code.replacing 文本,因为堆栈不允许我发布,主要是 code.replacing文本,因为堆栈不允许我发布,主要说代码.替换文本,因为堆栈不允许我发布,主要说代码.替换文本,因为堆栈不允许我发布,主要说代码.替换文本,因为堆栈不允许我发帖,主要说代码.替换文本,因为堆栈不允许我发帖,主要说代码.替换文本,因为堆栈不允许我发帖,主要说代码.替换文本,因为堆栈不让我发帖,主要说 code.replacing 文本,因为堆栈不让我发帖,主要说 code.replacing 文本,因为堆栈不让我post,主要是 code.replacing text,因为 stack 不允许我发布,主要是 code.replacing text,因为 stack 不允许我发布,主要是 code。

    static void Main(string[] args)
    
        var clientWeather = new RestClient("http://api.worldweatheronline.com/premium/v1/weather.ashx");//?key=c37f984779f14beb9bf01943201104&q=Pristina&format=json&num_of_days=5");
                                                                                                        //client.Timeout = -1;
        var requestWeather = new RestRequest(Method.GET);
        requestWeather.AddParameter("key", "c37f984779f14beb9bf01943201104", ParameterType.QueryString);
        requestWeather.AddParameter("q", "London", ParameterType.QueryString);
        requestWeather.AddParameter("format", "xml", ParameterType.QueryString);
        requestWeather.AddParameter("num_of_days", "5", ParameterType.QueryString);
        IRestResponse responseWeather = clientWeather.Execute(requestWeather);

        var xmlDeserializer = new XmlDeserializer();
        var place = xmlDeserializer.Deserialize<Request>(responseWeather);
        var temp = xmlDeserializer.Deserialize<Current_condition>(responseWeather);
        var dit = xmlDeserializer.Deserialize<Weather>(responseWeather);
        var data1 = xmlDeserializer.Deserialize<Data>(responseWeather);


        Console.WriteLine("Place: " + place.Query);
        Console.WriteLine("Temp momentale: " + temp.FeelsLikeC);

        Console.WriteLine("Temp for 5 days.");

        Console.Write("Date         " + "TempMin    " );
        Console.WriteLine("TempMax");

        Console.WriteLine(dit.Date + "      " + dit.MintempC + "    " + dit.MaxtempC);


        Console.ReadLine();













        Console.ReadLine();
    





    [XmlRoot(ElementName = "request")]
    public class Request
    
        [XmlElement(ElementName = "type")]
        public string Type  get; set; 
        [XmlElement(ElementName = "query")]
        public string Query  get; set; 
    

    [XmlRoot(ElementName = "current_condition")]
    public class Current_condition
    
        [XmlElement(ElementName = "observation_time")]
        public string Observation_time  get; set; 
        [XmlElement(ElementName = "temp_C")]
        public string Temp_C  get; set; 
        [XmlElement(ElementName = "temp_F")]
        public string Temp_F  get; set; 
        [XmlElement(ElementName = "weatherCode")]
        public string WeatherCode  get; set; 
        [XmlElement(ElementName = "weatherIconUrl")]
        public string WeatherIconUrl  get; set; 
        [XmlElement(ElementName = "weatherDesc")]
        public string WeatherDesc  get; set; 
        [XmlElement(ElementName = "windspeedMiles")]
        public string WindspeedMiles  get; set; 
        [XmlElement(ElementName = "windspeedKmph")]
        public string WindspeedKmph  get; set; 
        [XmlElement(ElementName = "winddirDegree")]
        public string WinddirDegree  get; set; 
        [XmlElement(ElementName = "winddir16Point")]
        public string Winddir16Point  get; set; 
        [XmlElement(ElementName = "precipMM")]
        public string PrecipMM  get; set; 
        [XmlElement(ElementName = "precipInches")]
        public string PrecipInches  get; set; 
        [XmlElement(ElementName = "humidity")]
        public string Humidity  get; set; 
        [XmlElement(ElementName = "visibility")]
        public string Visibility  get; set; 
        [XmlElement(ElementName = "visibilityMiles")]
        public string VisibilityMiles  get; set; 
        [XmlElement(ElementName = "pressure")]
        public string Pressure  get; set; 
        [XmlElement(ElementName = "pressureInches")]
        public string PressureInches  get; set; 
        [XmlElement(ElementName = "cloudcover")]
        public string Cloudcover  get; set; 
        [XmlElement(ElementName = "FeelsLikeC")]
        public string FeelsLikeC  get; set; 
        [XmlElement(ElementName = "FeelsLikeF")]
        public string FeelsLikeF  get; set; 
        [XmlElement(ElementName = "uvIndex")]
        public string UvIndex  get; set; 
    

    [XmlRoot(ElementName = "astronomy")]
    public class Astronomy
    
        [XmlElement(ElementName = "sunrise")]
        public string Sunrise  get; set; 
        [XmlElement(ElementName = "sunset")]
        public string Sunset  get; set; 
        [XmlElement(ElementName = "moonrise")]
        public string Moonrise  get; set; 
        [XmlElement(ElementName = "moonset")]
        public string Moonset  get; set; 
        [XmlElement(ElementName = "moon_phase")]
        public string Moon_phase  get; set; 
        [XmlElement(ElementName = "moon_illumination")]
        public string Moon_illumination  get; set; 
    

    [XmlRoot(ElementName = "hourly")]
    public class Hourly
    
        [XmlElement(ElementName = "time")]
        public string Time  get; set; 
        [XmlElement(ElementName = "tempC")]
        public string TempC  get; set; 
        [XmlElement(ElementName = "tempF")]
        public string TempF  get; set; 
        [XmlElement(ElementName = "windspeedMiles")]
        public string WindspeedMiles  get; set; 
        [XmlElement(ElementName = "windspeedKmph")]
        public string WindspeedKmph  get; set; 
        [XmlElement(ElementName = "winddirDegree")]
        public string WinddirDegree  get; set; 
        [XmlElement(ElementName = "winddir16Point")]
        public string Winddir16Point  get; set; 
        [XmlElement(ElementName = "weatherCode")]
        public string WeatherCode  get; set; 
        [XmlElement(ElementName = "weatherIconUrl")]
        public string WeatherIconUrl  get; set; 
        [XmlElement(ElementName = "weatherDesc")]
        public string WeatherDesc  get; set; 
        [XmlElement(ElementName = "precipMM")]
        public string PrecipMM  get; set; 
        [XmlElement(ElementName = "precipInches")]
        public string PrecipInches  get; set; 
        [XmlElement(ElementName = "humidity")]
        public string Humidity  get; set; 
        [XmlElement(ElementName = "visibility")]
        public string Visibility  get; set; 
        [XmlElement(ElementName = "visibilityMiles")]
        public string VisibilityMiles  get; set; 
        [XmlElement(ElementName = "pressure")]
        public string Pressure  get; set; 
        [XmlElement(ElementName = "pressureInches")]
        public string PressureInches  get; set; 
        [XmlElement(ElementName = "cloudcover")]
        public string Cloudcover  get; set; 
        [XmlElement(ElementName = "HeatIndexC")]
        public string HeatIndexC  get; set; 
        [XmlElement(ElementName = "HeatIndexF")]
        public string HeatIndexF  get; set; 
        [XmlElement(ElementName = "DewPointC")]
        public string DewPointC  get; set; 
        [XmlElement(ElementName = "DewPointF")]
        public string DewPointF  get; set; 
        [XmlElement(ElementName = "WindChillC")]
        public string WindChillC  get; set; 
        [XmlElement(ElementName = "WindChillF")]
        public string WindChillF  get; set; 
        [XmlElement(ElementName = "WindGustMiles")]
        public string WindGustMiles  get; set; 
        [XmlElement(ElementName = "WindGustKmph")]
        public string WindGustKmph  get; set; 
        [XmlElement(ElementName = "FeelsLikeC")]
        public string FeelsLikeC  get; set; 
        [XmlElement(ElementName = "FeelsLikeF")]
        public string FeelsLikeF  get; set; 
        [XmlElement(ElementName = "chanceofrain")]
        public string Chanceofrain  get; set; 
        [XmlElement(ElementName = "chanceofremdry")]
        public string Chanceofremdry  get; set; 
        [XmlElement(ElementName = "chanceofwindy")]
        public string Chanceofwindy  get; set; 
        [XmlElement(ElementName = "chanceofovercast")]
        public string Chanceofovercast  get; set; 
        [XmlElement(ElementName = "chanceofsunshine")]
        public string Chanceofsunshine  get; set; 
        [XmlElement(ElementName = "chanceoffrost")]
        public string Chanceoffrost  get; set; 
        [XmlElement(ElementName = "chanceofhightemp")]
        public string Chanceofhightemp  get; set; 
        [XmlElement(ElementName = "chanceoffog")]
        public string Chanceoffog  get; set; 
        [XmlElement(ElementName = "chanceofsnow")]
        public string Chanceofsnow  get; set; 
        [XmlElement(ElementName = "chanceofthunder")]
        public string Chanceofthunder  get; set; 
        [XmlElement(ElementName = "uvIndex")]
        public string UvIndex  get; set; 
    

    [XmlRoot(ElementName = "weather")]
    public class Weather
    
        [XmlElement(ElementName = "date")]
        public string Date  get; set; 
        [XmlElement(ElementName = "astronomy")]
        public Astronomy Astronomy  get; set; 
        [XmlElement(ElementName = "maxtempC")]
        public string MaxtempC  get; set; 
        [XmlElement(ElementName = "maxtempF")]
        public string MaxtempF  get; set; 
        [XmlElement(ElementName = "mintempC")]
        public string MintempC  get; set; 
        [XmlElement(ElementName = "mintempF")]
        public string MintempF  get; set; 
        [XmlElement(ElementName = "avgtempC")]
        public string AvgtempC  get; set; 
        [XmlElement(ElementName = "avgtempF")]
        public string AvgtempF  get; set; 
        [XmlElement(ElementName = "totalSnow_cm")]
        public string TotalSnow_cm  get; set; 
        [XmlElement(ElementName = "sunHour")]
        public string SunHour  get; set; 
        [XmlElement(ElementName = "uvIndex")]
        public string UvIndex  get; set; 
        [XmlElement(ElementName = "hourly")]
        public List<Hourly> Hourly  get; set; 
    

    [XmlRoot(ElementName = "month")]
    public class Month
    
        [XmlElement(ElementName = "index")]
        public string Index  get; set; 
        [XmlElement(ElementName = "name")]
        public string Name  get; set; 
        [XmlElement(ElementName = "avgMinTemp")]
        public string AvgMinTemp  get; set; 
        [XmlElement(ElementName = "avgMinTemp_F")]
        public string AvgMinTemp_F  get; set; 
        [XmlElement(ElementName = "absMaxTemp")]
        public string AbsMaxTemp  get; set; 
        [XmlElement(ElementName = "absMaxTemp_F")]
        public string AbsMaxTemp_F  get; set; 
        [XmlElement(ElementName = "avgDailyRainfall")]
        public string AvgDailyRainfall  get; set; 
    

    [XmlRoot(ElementName = "ClimateAverages")]
    public class ClimateAverages
    
        [XmlElement(ElementName = "month")]
        public List<Month> Month  get; set; 
    

    [XmlRoot(ElementName = "data")]
    public class Data
    
        [XmlElement(ElementName = "request")]
        public Request Request  get; set; 
        [XmlElement(ElementName = "current_condition")]
        public Current_condition Current_condition  get; set; 
        [XmlElement(ElementName = "weather")]
        public List<Weather> Weather  get; set; 
        [XmlElement(ElementName = "ClimateAverages")]
        public ClimateAverages ClimateAverages  get; set; 
    



【问题讨论】:

为什么在你的问题中出现重复文字的大墙? 如果那是您真正的 API 密钥,我建议您删除它 - 公开发布真正的 API 密钥是一种危险的事情。 【参考方案1】:

您可以将 xml 反序列化为特定对象的集合,如下所示:

//request and response code omitted for brevity

var dit = xmlDeserializer.Deserialize<List<Weather>>(responseWeather);

foreach(var date in dit)

     Console.WriteLine(date.Date + "      " + date.MintempC + "    " + date.MaxtempC);

输出:

2020-04-20      9    15
2020-04-21      9    15
2020-04-22      11    16
2020-04-23      12    20
2020-04-24      11    19

【讨论】:

谢谢您,先生,您有我的尊重 :) .【参考方案2】:

我修改了网址。你得到的是 json 而不是 xml。请参阅下面的 xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;

namespace ConsoleApplication1

    class Program
    
        const string URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c37f984779f14beb9bf01943201104&q=Pristina&num_of_days=5";
        static void Main(string[] args)
        
            XDocument doc = XDocument.Load(URL);
            List<TemperatureDate> dates = doc.Descendants("weather").Select(x => new TemperatureDate()
            
                date = (DateTime)x.Element("date"),
                avgtempF = (int)x.Element("avgtempF"),
                hourTemp = x.Elements("hourly").Select(y => new KeyValuePair<int,int>(((int)y.Element("time"))/100, (int)y.Element("tempF"))).ToList()
            ).ToList();

       
    
    public class TemperatureDate
    
        public DateTime date  get; set; 
        public int avgtempF  get; set; 
        public List<KeyValuePair<int, int>> hourTemp  get; set;  
    

使用序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1

    class Program
    
        const string URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c37f984779f14beb9bf01943201104&q=Pristina&num_of_days=5";
        static void Main(string[] args)
        
            XmlReader reader = XmlReader.Create(URL);
            XmlSerializer serializer = new XmlSerializer(typeof(data));
            data data = (data)serializer.Deserialize(reader);
        
    
    public class data
    
        public request request   get; set; 
        public current_condition current_condition  get; set; 
        public weather weather  get; set; 
    
    public class request
    
        [XmlElement("type")]
        public string _type  get; set; 
        public string query  get; set; 
    
    public class current_condition
    
        public TimeSpan observation_time  get; set; 
        public int temp_C  get; set; 
        public int temp_F  get; set; 
        public int weatherCode  get; set; 
        public string weatherIconUrl  get; set; 
        public string weatherDesc  get; set; 
        public int windspeedMiles  get; set; 
        public int windspeedKmph  get; set; 
        public int winddirDegree  get; set; 
        public string winddir16Point  get; set; 
        public  decimal precipMM  get; set; 
        public decimal precipInches  get; set; 
        public int humidity  get; set; 
        public int visibility  get; set; 
        public int visibilityMiles  get; set; 
        public int pressure  get; set; 
        public int pressureInches  get; set; 
        public int cloudcover  get; set; 
        public int FeelsLikeC  get; set; 
        public int FeelsLikeF  get; set; 
        public int uvIndex  get; set; 
    

    public class weather
    
        public DateTime date  get; set; 
        public astronomy astronomy  get; set; 
        public int maxtempC  get; set; 
        public int maxtempF  get; set; 
        public int mintempC  get; set; 
        public int mintempF  get; set; 
        public int avgtempC  get; set; 
        public int avgtempF  get; set; 
        public decimal totalSnow_cm  get; set; 
        public decimal sunHour  get; set; 
        public int uvIndex  get; set; 
        [XmlElement("hourly")]
        public List<hourly> hourly  get; set; 
    
    public class astronomy
    
      public TimeSpan sunrise  get; set; 
      public TimeSpan sunset  get; set; 
      public TimeSpan moonrise  get; set; 
      public TimeSpan moonset  get; set; 
      public string moon_phase  get; set; 
      public int moon_illumination  get; set; 
    
    public class hourly
    
      public int time  get; set; 
      public int tempC  get; set; 
      public int tempF  get; set; 
      public int windspeedMiles  get; set; 
      public int windspeedKmph  get; set; 
      public int winddirDegree  get; set; 
      public string winddir16Point  get; set; 
      public int weatherCode  get; set; 
      public string weatherIconUrl  get; set; 
      public string weatherDesc  get; set; 
      public decimal precipMM  get; set; 
      public decimal precipInches  get; set; 
      public int humidity  get; set; 
      public int visibility  get; set; 
      public int visibilityMiles  get; set; 
      public int pressure  get; set; 
      public int pressureInches  get; set; 
      public int cloudcover  get; set; 
      public int HeatIndexC  get; set; 
      public int HeatIndexF  get; set; 
      public int DewPointC  get; set; 
      public int DewPointF  get; set; 
      public int WindChillC  get; set; 
      public int WindChillF  get; set; 
      public int WindGustMiles  get; set; 
      public int WindGustKmph  get; set; 
      public int FeelsLikeC  get; set; 
      public int FeelsLikeF  get; set; 
      public int chanceofrain  get; set; 
      public int chanceofremdry  get; set; 
      public int chanceofwindy  get; set; 
      public int chanceofovercast  get; set; 
      public int chanceofsunshine  get; set; 
      public int chanceoffrost  get; set; 
      public int chanceofhightemp  get; set; 
      public int chanceoffog  get; set; 
      public int chanceofsnow  get; set; 
      public int chanceofthunder  get; set; 
      public int uvIndex  get; set; 
    

【讨论】:

非常感谢,但它也是我需要 XmlSerializer 的 XML。 - requestWeather.AddParameter("format", "xml", ParameterType.QueryString); Xml 是默认值。您在 cmets 中有 json。我更新了 xml 序列化的代码

以上是关于如何从 Weather API XML 打印所有日期的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Yahoo Weather API 从 IP 地址获取客户端天气

您如何从 Azure Active Directory 中获取搭建的 Weather Forecast Api 将接受的访问令牌?

我想从网站 http://www.weather.gov/forecasts/xml [重复] 检索数据

无法从 Flutter 中的 Open Weather API 获取数据

如何在 API Weather - Sunrise/Sunset 中转换数据?

三行PHP中的当前天气