Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.86/7: Рейтинг темы: голосов - 7, средняя оценка - 4.86
4 / 3 / 1
Регистрация: 06.04.2020
Сообщений: 76

АПИ погоды

06.06.2021, 22:24. Показов 1526. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте! Нужно из api погоды взять значения: мин. температура, макс. температура и состояние атмосферы на 3 дня. Не знаю как упростить код, в плане, возможно ли избавиться от больших проверок и цыклов используя, например, linq или лямбды. Подскажите пожалуйста.

api - http://api.pogoda.com/index.ph... 7j6at7rkya

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Net;
using System.Text;
 
namespace ConsoleApplication3
{
    internal class Program
    {
        struct WeatherOne
        {
            public int minT;
            public int maxT;
            public int windSpeed;
            public string cloudy;
        }
 
        struct WeatherTwo
        {
            public int minT;
            public int maxT;
            public int windSpeed;
            public string cloudy;
        }
        
        struct WeatherThree
        {
            public int minT;
            public int maxT;
            public int windSpeed;
            public string cloudy;
        }
        
        public static void Main(string[] args)
        {
            List<int> list = new List<int>();
            List<string> listCloudy = new List<string>();
            
            
            WeatherOne one;
            one.minT = 0;
            one.maxT = 0;
            one.windSpeed = 0;
            one.cloudy = null;
            
            WeatherTwo two;
            two.minT = 0;
            two.maxT = 0;
            two.windSpeed = 0;
            two.cloudy = null;
            
            WeatherThree three;
            three.minT = 0;
            three.maxT = 0;
            three.windSpeed = 0;
            three.cloudy = null;
            
            bool minTemp = false;
            bool maxTemp = false;
            bool cloudy = false;
            bool wind = false;
            
            
            string path = @"http://api.pogoda.com/index.php?api_lang=ru&localidad=13088&affiliate_id=4v7j6at7rkya";
            using (var webClient = new WebClient() {Encoding = Encoding.UTF8})
            {
                webClient.DownloadFile(path,"weather.xml");
            }
            
            try
            {
                using (var reader = new XmlTextReader("weather.xml"))
                {
                    while (reader.Read())
                    {
                        if (reader.Value == "Мин. температура")
                        {
                            minTemp = true;
                        }
 
                        if (minTemp)
                        {
                            if (reader.Name =="forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                list.Add(int.Parse(reader.Value));
                                if (list.Count == 3)
                                {
                                    one.minT = list[0];
                                    two.minT = list[1];
                                    three.minT = list[2];
                                    minTemp = false;
                                }
                            }
                        }
                        if (reader.Value == "Макс. температура")
                        {
                            maxTemp = true;
                        }
                        
                        if (maxTemp)
                        {
                            if (reader.Name =="forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                list.Add(int.Parse(reader.Value));
                                if (list.Count == 6)
                                {
                                    maxTemp = false;
                                    one.maxT = list[3];
                                    two.maxT = list[4];
                                    three.maxT = list[5];
                                    
                                }
                            }
                        }
                       
                        
                        if (reader.Value == "Ветер")
                        {
                            wind = true;
                        }
                        
                        if (wind)
                        {
                            if (reader.Name =="forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                list.Add(int.Parse(reader.Value));
                                if (list.Count == 9)
                                {
                                    one.windSpeed = list[6];
                                    two.windSpeed = list[7];
                                    three.windSpeed = list[8];
                                    wind = false;
                                }
                                
                                
                                
                            }
                            
                        }
                        
                        
                        
                        if (reader.Value == "Состояние атмосферы")
                        {
                            cloudy = true;
                        }
                        
                        if (cloudy)
                        {
                            if (reader.Name =="forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                
                                listCloudy.Add(reader.Value);
                                if (listCloudy.Count == 3)
                                {
                                    one.cloudy = listCloudy[0];
                                    two.cloudy = listCloudy[1];
                                    three.cloudy = listCloudy[2];
                                    cloudy = false;
                                }
                              
                                
                            }
                            
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error - {e.Message}");
            }
           
            Console.WriteLine($"Сегодня - Мин. температура: {one.minT}, Макс. температура: {one.maxT}, Скорость ветра: {one.windSpeed}, Состояние атмосферы: {one.cloudy}");
            Console.WriteLine($"Завтра - Мин. температура: {two.minT}, Макс. температура: {two.maxT}, Скорость ветра: {two.windSpeed}, Состояние атмосферы: {two.cloudy}");
            Console.WriteLine($"Послезавтра - Мин. температура: {three.minT}, Макс. температура: {three.maxT}, Скорость ветра: {three.windSpeed}, Состояние атмосферы: {three.cloudy}");
            
        }
    }
}
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
06.06.2021, 22:24
Ответы с готовыми решениями:

АПИ: new Car().Run(100)
Здравствуйте! У меня есть задача: есть машина и велосипед, у машины макс. скорость 300 км/ч, у велосипеда 40 км/ч, надо реализовать...

Прогноз погоды
Доброго времени суток! Пишу гаджет - средневзвешенный прогноз погоды с рейтингом доверия для каждого метео-портала. Уже пропарсил 2 сайта...

Парсинг погоды
Доброго времени суток! Пишу бота на VK, хочу что бы на слово: &quot;погода в Москве, погода в Казани, погода в Кирове, погода в Санкт -...

2
Злой няш
 Аватар для I2um1
2136 / 1505 / 565
Регистрация: 05.04.2010
Сообщений: 2,881
07.06.2021, 00:36
Лучший ответ Сообщение было отмечено ForNazar как решение

Решение

ForNazar, можно начать с замены трех структур на классы, убрать их начальную инициализацию и реализовать ToString, чтобы избавиться от дублирования строк 185-187.
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Net;
using System.Text;
 
namespace ConsoleApplication3
{
    public static class Program
    {
        public class Weather
        {
            public int MinT { get; set; }
            public int MaxT { get; set; }
            public int WindSpeed { get; set; }
            public string Cloudy { get; set; }
 
            public override string ToString()
            {
                return $"Мин. температура: {MinT}, "
                    + $"Макс. температура: {MaxT}, "
                    + $"Скорость ветра: {WindSpeed}, "
                    + $"Состояние атмосферы: {Cloudy}";
            }
        }
 
        public static void Main(string[] args)
        {
            List<int> list = new List<int>();
            List<string> listCloudy = new List<string>();
 
            Weather one = new Weather();
            Weather two = new Weather();
            Weather three = new Weather();
 
            bool minTemp = false;
            bool maxTemp = false;
            bool cloudy = false;
            bool wind = false;
 
            string path = @"http://api.pogoda.com/index.php?api_lang=ru&localidad=13088&affiliate_id=4v7j6at7rkya";
            using (var webClient = new WebClient() { Encoding = Encoding.UTF8 })
            {
                webClient.DownloadFile(path, "weather.xml");
            }
 
            try
            {
                using (var reader = new XmlTextReader("weather.xml"))
                {
                    while (reader.Read())
                    {
                        if (reader.Value == "Мин. температура")
                        {
                            minTemp = true;
                        }
 
                        if (minTemp)
                        {
                            if (reader.Name == "forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                list.Add(int.Parse(reader.Value));
                                if (list.Count == 3)
                                {
                                    one.MinT = list[0];
                                    two.MinT = list[1];
                                    three.MinT = list[2];
                                    minTemp = false;
                                }
                            }
                        }
                        if (reader.Value == "Макс. температура")
                        {
                            maxTemp = true;
                        }
 
                        if (maxTemp)
                        {
                            if (reader.Name == "forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                list.Add(int.Parse(reader.Value));
                                if (list.Count == 6)
                                {
                                    maxTemp = false;
                                    one.MaxT = list[3];
                                    two.MaxT = list[4];
                                    three.MaxT = list[5];
 
                                }
                            }
                        }
 
 
                        if (reader.Value == "Ветер")
                        {
                            wind = true;
                        }
 
                        if (wind)
                        {
                            if (reader.Name == "forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
                                list.Add(int.Parse(reader.Value));
                                if (list.Count == 9)
                                {
                                    one.WindSpeed = list[6];
                                    two.WindSpeed = list[7];
                                    three.WindSpeed = list[8];
                                    wind = false;
                                }
 
 
 
                            }
 
                        }
 
 
 
                        if (reader.Value == "Состояние атмосферы")
                        {
                            cloudy = true;
                        }
 
                        if (cloudy)
                        {
                            if (reader.Name == "forecast")
                            {
                                reader.MoveToNextAttribute();
                                reader.MoveToNextAttribute();
 
                                listCloudy.Add(reader.Value);
                                if (listCloudy.Count == 3)
                                {
                                    one.Cloudy = listCloudy[0];
                                    two.Cloudy = listCloudy[1];
                                    three.Cloudy = listCloudy[2];
                                    cloudy = false;
                                }
 
 
                            }
 
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error - {e.Message}");
            }
 
            Console.WriteLine($"Сегодня - {one}");
            Console.WriteLine($"Завтра - {two}");
            Console.WriteLine($"Послезавтра - {three}");
 
        }
    }
}
Далее переменные объединить в массив, не создавать файлы, заменить XmlTextReader на XmlDocument:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Net;
using System.Text;
 
namespace ConsoleApplication3
{
    public static class Program
    {
        public class Weather
        {
            public int MinT { get; set; }
            public int MaxT { get; set; }
            public int WindSpeed { get; set; }
            public string Cloudy { get; set; }
 
            public override string ToString()
            {
                return $"Мин. температура: {MinT}, "
                    + $"Макс. температура: {MaxT}, "
                    + $"Скорость ветра: {WindSpeed}, "
                    + $"Состояние атмосферы: {Cloudy}";
            }
        }
 
        public static void Main()
        {
            Weather[] weatherArray = new Weather[3];
            weatherArray[0] = new Weather();
            weatherArray[1] = new Weather();
            weatherArray[2] = new Weather();
 
            string path = @"http://api.pogoda.com/index.php?api_lang=ru&localidad=13088&affiliate_id=4v7j6at7rkya";
            string xmlText;
            using (var webClient = new WebClient() { Encoding = Encoding.UTF8 })
            {
                xmlText = webClient.DownloadString(path);
            }
 
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xmlText);
 
                XmlNodeList minTemperatureList = xmlDocument.SelectNodes("//var[1]/data/forecast/@value");
                weatherArray[0].MinT = int.Parse(minTemperatureList.Item(0).InnerText);
                weatherArray[1].MinT = int.Parse(minTemperatureList.Item(1).InnerText);
                weatherArray[2].MinT = int.Parse(minTemperatureList.Item(2).InnerText);
 
                XmlNodeList maxTemperatureList = xmlDocument.SelectNodes("//var[2]/data/forecast/@value");
                weatherArray[0].MaxT = int.Parse(maxTemperatureList.Item(0).InnerText);
                weatherArray[1].MaxT = int.Parse(maxTemperatureList.Item(1).InnerText);
                weatherArray[2].MaxT = int.Parse(maxTemperatureList.Item(2).InnerText);
 
                XmlNodeList windSpeedList = xmlDocument.SelectNodes("//var[3]/data/forecast/@idB");
                weatherArray[0].WindSpeed = int.Parse(windSpeedList.Item(0).InnerText);
                weatherArray[1].WindSpeed = int.Parse(windSpeedList.Item(1).InnerText);
                weatherArray[2].WindSpeed = int.Parse(windSpeedList.Item(2).InnerText);
 
                XmlNodeList cloudyList = xmlDocument.SelectNodes("//var[6]/data/forecast/@value");
                weatherArray[0].Cloudy = cloudyList.Item(0).InnerText;
                weatherArray[1].Cloudy = cloudyList.Item(1).InnerText;
                weatherArray[2].Cloudy = cloudyList.Item(2).InnerText;
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error - {e.Message}");
            }
 
            Console.WriteLine($"Сегодня - {weatherArray[0]}");
            Console.WriteLine($"Завтра - {weatherArray[1]}");
            Console.WriteLine($"Послезавтра - {weatherArray[2]}");
        }
    }
}
Затем заменить XPath магию на десериализацию в объект:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using System.IO;
 
namespace ConsoleApplication3
{
    public static class Program
    {
        public static void Main()
        {
            Weather[] weatherArray = new Weather[3];
            weatherArray[0] = new Weather();
            weatherArray[1] = new Weather();
            weatherArray[2] = new Weather();
 
            string path = @"http://api.pogoda.com/index.php?api_lang=ru&localidad=13088&affiliate_id=4v7j6at7rkya";
            string xmlText;
            using (var webClient = new WebClient() { Encoding = Encoding.UTF8 })
            {
                xmlText = webClient.DownloadString(path);
            }
 
            try
            {
                Report report;
                XmlSerializer serializer = new XmlSerializer(typeof(Report));
                using (TextReader reader = new StringReader(xmlText))
                {
                    report = (Report)serializer.Deserialize(reader);
                }
 
                LocationParameter[] parameters = report.Locations[0].Parameters;
 
                Forecast[] minTemperatureList = parameters.First(x => x.Name == "Мин. температура").Data;
                for (int i = 0; i < weatherArray.Length; i++)
                {
                    weatherArray[i].MinT = int.Parse(minTemperatureList[i].Value);
                }
 
                Forecast[] maxTemperatureList = parameters.First(x => x.Name == "Макс. температура").Data;
                for (int i = 0; i < weatherArray.Length; i++)
                {
                    weatherArray[i].MaxT = int.Parse(maxTemperatureList[i].Value);
                }
 
                Forecast[] windSpeedList = parameters.First(x => x.Name == "Ветер").Data;
                for (int i = 0; i < weatherArray.Length; i++)
                {
                    weatherArray[i].WindSpeed = int.Parse(windSpeedList[i].IdB);
                }
 
                Forecast[] cloudyList = parameters.First(x => x.Name == "Состояние атмосферы").Data;
                for (int i = 0; i < weatherArray.Length; i++)
                {
                    weatherArray[i].Cloudy = cloudyList[i].Value;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error - {e.Message}");
            }
 
            Console.WriteLine($"Сегодня - {weatherArray[0]}");
            Console.WriteLine($"Завтра - {weatherArray[1]}");
            Console.WriteLine($"Послезавтра - {weatherArray[2]}");
        }
    }
 
    public class Weather
    {
        public int MinT { get; set; }
        public int MaxT { get; set; }
        public int WindSpeed { get; set; }
        public string Cloudy { get; set; }
 
        public override string ToString()
        {
            return $"Мин. температура: {MinT}, "
                + $"Макс. температура: {MaxT}, "
                + $"Скорость ветра: {WindSpeed}, "
                + $"Состояние атмосферы: {Cloudy}";
        }
    }
 
    [XmlRoot("report")]
    public class Report
    {
        [XmlElement("location")]
        public Location[] Locations { get; set; }
    }
 
    public class Location
    {
        [XmlAttribute("city")]
        public string City { get; set; }
 
        [XmlElement("var")]
        public LocationParameter[] Parameters { get; set; }
    }
 
    public class LocationParameter
    {
        [XmlElement("name")]
        public string Name { get; set; }
 
        [XmlArray("data")]
        [XmlArrayItem("forecast")]
        public Forecast[] Data { get; set; }
    }
 
    public class Forecast
    {
        [XmlAttribute("value")]
        public string Value { get; set; }
 
        [XmlAttribute("idB")]
        public string IdB { get; set; }
    }
}
Убрать дублирование:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
 
namespace ConsoleApplication
{
    public static class Program
    {
        public static void Main()
        {
            Weather[] weatherArray = { new Weather(), new Weather(), new Weather() };
            try
            {
                var reportXml = DownloadReport(@"http://api.pogoda.com/index.php?api_lang=ru&localidad=13088&affiliate_id=4v7j6at7rkya");
                Report report = DeserializeReport(reportXml);
                LocationParameter[] parameters = report.Locations[0].Parameters;
                SetForecastParameters(weatherArray, parameters);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error - {e.Message}");
            }
 
            Console.WriteLine($"Сегодня - {weatherArray[0]}");
            Console.WriteLine($"Завтра - {weatherArray[1]}");
            Console.WriteLine($"Послезавтра - {weatherArray[2]}");
        }
 
        private static void SetForecastParameters(Weather[] weatherArray, LocationParameter[] parameters)
        {
            Action<Weather, Forecast> setMinT = (weather, forecast) => weather.MinT = int.Parse(forecast.Value);
            Action<Weather, Forecast> setMaxT = (weather, forecast) => weather.MaxT = int.Parse(forecast.Value);
            Action<Weather, Forecast> setWindSpeed = (weather, forecast) => weather.WindSpeed = int.Parse(forecast.IdB);
            Action<Weather, Forecast> setCloudy = (weather, forecast) => weather.Cloudy = forecast.Value;
 
            SetForecastParameter(weatherArray, parameters, "Мин. температура", setMinT);
            SetForecastParameter(weatherArray, parameters, "Макс. температура", setMaxT);
            SetForecastParameter(weatherArray, parameters, "Ветер", setWindSpeed);
            SetForecastParameter(weatherArray, parameters, "Состояние атмосферы", setCloudy);
        }
 
        private static void SetForecastParameter(
            Weather[] weatherArray,
            LocationParameter[] parameters,
            string parameterName,
            Action<Weather, Forecast> setAction)
        {
            Forecast[] data = parameters.First(x => x.Name == parameterName).Data;
            for (var i = 0; i < weatherArray.Length; i++)
            {
                setAction(weatherArray[i], data[i]);
            }
        }
 
        private static string DownloadReport(string url)
        {
            using (var webClient = new WebClient { Encoding = Encoding.UTF8 })
            {
                return webClient.DownloadString(url);
            }
        }
 
        private static Report DeserializeReport(string xml)
        {
            var serializer = new XmlSerializer(typeof(Report));
            using (TextReader reader = new StringReader(xml))
            {
                return (Report)serializer.Deserialize(reader);
            }
        }
    }
 
    public class Weather
    {
        public int MinT { get; set; }
        public int MaxT { get; set; }
        public int WindSpeed { get; set; }
        public string Cloudy { get; set; }
 
        public override string ToString()
        {
            return $"Мин. температура: {MinT}, "
                + $"Макс. температура: {MaxT}, "
                + $"Скорость ветра: {WindSpeed}, "
                + $"Состояние атмосферы: {Cloudy}";
        }
    }
 
    [XmlRoot("report")]
    public class Report
    {
        [XmlElement("location")]
        public Location[] Locations { get; set; }
    }
 
    public class Location
    {
        [XmlAttribute("city")]
        public string City { get; set; }
 
        [XmlElement("var")]
        public LocationParameter[] Parameters { get; set; }
    }
 
    public class LocationParameter
    {
        [XmlElement("name")]
        public string Name { get; set; }
 
        [XmlArray("data")]
        [XmlArrayItem("forecast")]
        public Forecast[] Data { get; set; }
    }
 
    public class Forecast
    {
        [XmlAttribute("value")]
        public string Value { get; set; }
 
        [XmlAttribute("idB")]
        public string IdB { get; set; }
    }
}
И так далее, в коде еще много проблем.

Добавлено через 10 минут
ForNazar, если не хочется развивать SetForecastParameters дальше, то его можно чуть упростить:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
 
namespace ConsoleApplication
{
    public static class Program
    {
        public static void Main()
        {
            Weather[] weatherArray = { new Weather(), new Weather(), new Weather() };
            try
            {
                var reportXml = DownloadReport(@"http://api.pogoda.com/index.php?api_lang=ru&localidad=13088&affiliate_id=4v7j6at7rkya");
                Report report = DeserializeReport(reportXml);
                LocationParameter[] parameters = report.Locations[0].Parameters;
                SetForecastParameters(weatherArray, parameters);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error - {e.Message}");
            }
 
            Console.WriteLine($"Сегодня - {weatherArray[0]}");
            Console.WriteLine($"Завтра - {weatherArray[1]}");
            Console.WriteLine($"Послезавтра - {weatherArray[2]}");
        }
 
        private static void SetForecastParameters(Weather[] weatherArray, LocationParameter[] parameters)
        {
            Forecast[] minTParameters = parameters.First(x => x.Name == "Мин. температура").Data;
            Forecast[] maxTParameters = parameters.First(x => x.Name == "Макс. температура").Data;
            Forecast[] windSpeedParameters = parameters.First(x => x.Name == "Ветер").Data;
            Forecast[] cloudyParameters = parameters.First(x => x.Name == "Состояние атмосферы").Data;
 
            for (var i = 0; i < weatherArray.Length; i++)
            {
                weatherArray[i].MinT = int.Parse(minTParameters[i].Value);
                weatherArray[i].MaxT = int.Parse(maxTParameters[i].Value);
                weatherArray[i].WindSpeed = int.Parse(windSpeedParameters[i].IdB);
                weatherArray[i].Cloudy = cloudyParameters[i].Value;
            }
        }
 
        private static string DownloadReport(string url)
        {
            using (var webClient = new WebClient { Encoding = Encoding.UTF8 })
            {
                return webClient.DownloadString(url);
            }
        }
 
        private static Report DeserializeReport(string xml)
        {
            var serializer = new XmlSerializer(typeof(Report));
            using (TextReader reader = new StringReader(xml))
            {
                return (Report)serializer.Deserialize(reader);
            }
        }
    }
 
    public class Weather
    {
        public int MinT { get; set; }
        public int MaxT { get; set; }
        public int WindSpeed { get; set; }
        public string Cloudy { get; set; }
 
        public override string ToString()
        {
            return $"Мин. температура: {MinT}, "
                + $"Макс. температура: {MaxT}, "
                + $"Скорость ветра: {WindSpeed}, "
                + $"Состояние атмосферы: {Cloudy}";
        }
    }
 
    [XmlRoot("report")]
    public class Report
    {
        [XmlElement("location")]
        public Location[] Locations { get; set; }
    }
 
    public class Location
    {
        [XmlAttribute("city")]
        public string City { get; set; }
 
        [XmlElement("var")]
        public LocationParameter[] Parameters { get; set; }
    }
 
    public class LocationParameter
    {
        [XmlElement("name")]
        public string Name { get; set; }
 
        [XmlArray("data")]
        [XmlArrayItem("forecast")]
        public Forecast[] Data { get; set; }
    }
 
    public class Forecast
    {
        [XmlAttribute("value")]
        public string Value { get; set; }
 
        [XmlAttribute("idB")]
        public string IdB { get; set; }
    }
}
1
4 / 3 / 1
Регистрация: 06.04.2020
Сообщений: 76
07.06.2021, 08:32  [ТС]
Спасибо за помощь!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
07.06.2021, 08:32
Помогаю со студенческими работами здесь

Подскажите как сделать запрос к яндекс апи переводчику
Делаю запрос, на получения списка языков от апи яндекс переводчика, но почему то не работает подскажите как правильно сделать. Суть в том...

Парсинг страницы погоды
Доброго времени суток Материала на эту тему много, но он очень сложен для восприятия особенно чайнику новичку Нужно спарсить...

Перевести из C++ в C#: прогноз погоды
Помогите пожалуйста перевести код,пробовал сам,ничего не вышло. Суть задачи состоит в том, что необходимо реализовать клиент-серверное...

Обработка XML Яндекс Погоды
Сейчас обновили ресурс Погоды Яндекс - https://export.yandex.ru/bar/reginfo.xml?region=10487 И я не знаю как взять значения Элемента....

Определение и запись погоды по геотегу
Пишемь программу на с#. Все хорошо, но нужно теперь сделать что бы программа через гугл-погоду находила погоду в местности пользователя и...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru