Парсинг файла XML - C#
Формулировка задачи:
Помогите разобраться с парсингом файла XML.
На входе есть XML-файл:
Надо из него распарсить значения.
Есть метод, но не получается вытянуть город (City).
Какой метод XElement нужно использовать, чтобы достучаться ко всем данным?
Листинг программы
- <weatherdata>
- <location>
- <name>London</name>
- <type/>
- <country>GB</country>
- <timezone/>
- <location altitude="0" latitude="51.50853" longitude="-0.12574" geobase="geonames" geobaseid="2643743"/>
- </location>
- <credit/>
- <meta>
- <lastupdate/>
- <calctime>0.0102</calctime>
- <nextupdate/>
- </meta>
- <sun rise="2016-02-17T07:10:09" set="2016-02-17T17:19:37"/>
- <forecast>
- <time day="2016-02-17">
- <symbol number="501" name="moderate rain" var="10d"/>
- <precipitation value="6.82" type="rain"/>
- <windDirection deg="184" code="S" name="South"/>
- <windSpeed mps="4.47" name="Gentle Breeze"/>
- <temperature day="4.53" min="2.66" max="4.53" night="2.73" eve="4.53" morn="4.53"/>
- <pressure unit="hPa" value="1017.35"/>
- <humidity value="85" unit="%"/>
- <clouds value="overcast clouds" all="92" unit="%"/>
- </time>
- </forecast>
- </weatherdata>
Листинг программы
- public static async Task<List<WeatherModel>> GetWeather(string city)
- {
- string url =$"http://api.openweathermap.org/data/2.5/forecast/daily?q={city}&type=accurate&mode=xml&units=metric&cnt=1&appid={AppID}";
- using (HttpClient client = new HttpClient())
- {
- string rezult = await client.GetStringAsync(url);
- XElement xEl = XElement.Load(new System.IO.StringReader(rezult));
- IEnumerable<WeatherModel> weather = xmlElement.Descendants("time").Select((element) =>
- new WeatherModel
- {
- Day = element.Attribute("day").Value,
- DayOfWeek = DayOfWeekFill(element),
- WeatherName = element.Element("symbol").Attribute("name").Value,
- WindDirectionName = element.Element("windDirection").Attribute("name").Value,
- WindSpeedMps = element.Element("windSpeed").Attribute("mps").Value + "mps",
- TemperatureDay = element.Element("temperature").Attribute("day").Value + "°",
- TemperatureNight = element.Element("temperature").Attribute("night").Value + "°",
- TemperatureMorning = element.Element("temperature").Attribute("morn").Value + "°",
- MaxTemperature = element.Element("temperature").Attribute("max").Value + "°",
- MinTemperature = element.Element("temperature").Attribute("min").Value + "°",
- Humidity = element.Element("humidity").Attribute("value").Value + "%"
- //WeatherPicture = WeatherPictureFill(el),
- });
- return weather.ToList();
- }
- }
Решение задачи: «Парсинг файла XML»
textual
Листинг программы
- XDocument document = XDocument.Parse(rezult);
- XElement weatherElements = document.Element("weatherdata");
- IEnumerable<XElement> el = weatherElements.DescendantsAndSelf("weatherdata");
- weatherList = (from itm in el
- select new WeatherModel()
- {
- City = itm.Element("location").Element("name").Value,
- Day = itm.Element("forecast").Element("time").Attribute("day").Value,
- WeatherName = itm.Element("forecast").Element("time").Element("symbol").Attribute("name").Value,
- WindDirectionName = itm.Element("forecast").Element("time").Element("windDirection").Attribute("name").Value,
- WindSpeedMps = "Wind Speed\n" + itm.Element("forecast").Element("time").Element("windSpeed").Attribute("mps").Value + "mps",
- TemperatureDay = itm.Element("forecast").Element("time").Element("temperature").Attribute("day").Value + "°",
- TemperatureNight = itm.Element("forecast").Element("time").Element("temperature").Attribute("night").Value + "°",
- TemperatureMorning = itm.Element("forecast").Element("time").Element("temperature").Attribute("morn").Value + "°",
- Humidity = "Humidity\n" + itm.Element("forecast").Element("time").Element("humidity").Attribute("value").Value + "%",
- WeatherPicture = itm.Element("forecast").Element("time").Element("symbol").Attribute("name").Value;
- }).ToList();
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д