Answer the question
In order to leave comments, you need to log in
How to get the value of an xml tag in C#?
I'm new to C#, so far I'm doing it by examples, trying to modernize the code. But I got up, I don’t understand how to correctly extract the value of the cityname2 tag from this file: www.eurometeo.ru/russia/moskva/export/xml/data
Here is the code:
string sity = @"http://www.eurometeo.ru/russia/moskva/export/xml/data/";
string xmlData = new WebClient().DownloadString(sity);
var xmlColItems = XDocument.Parse(xmlData);
string text = xmlColItems.Descendants("weather")
.Descendants("city")
.Descendants("cityname2").ToString().Value;
Console.WriteLine(text);
Answer the question
In order to leave comments, you need to log in
Try swapping Value and ToString(). ToString() itself converts the object to a string, no further action on the string is needed.
string sity = @"http://www.eurometeo.ru/russia/moskva/export/xml/data/";
string xmlData = new WebClient().DownloadString(sity);
var xmlColItems = XDocument.Parse(xmlData);
var query = xmlColItems.Descendants("weather").Descendants("city").Select(p => new { c = p.Element("cityname2").Value }).ToList()[0];
string text = query.c.ToString();
byte[] bytes = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(1251), Encoding.Unicode.GetBytes(text));
text = Encoding.UTF8.GetString(bytes);
Console.WriteLine(text);
Try like this:
string text = xmlColItems.Descendants("weather")
.Descendants("city")
.Descendants("cityname2").FirstOrDefault()?.Value;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question