S
S
Senseich2018-03-21 22:01:36
C++ / C#
Senseich, 2018-03-21 22:01:36

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);

The tag itself (the element displays), but as a value, something does not work out. When adding .Value , it displays an error:
5ab2ab82b0e27779298966.jpeg
I still don’t really understand what this means, help me figure it out.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Smilley, 2018-03-21
@Smilley

Try swapping Value and ToString(). ToString() itself converts the object to a string, no further action on the string is needed.

M
Milton812, 2018-03-26
@milton812

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);

L
lvv85, 2018-03-22
@lvv85

Try like this:

string text = xmlColItems.Descendants("weather")
                                  .Descendants("city")
                                  .Descendants("cityname2").FirstOrDefault()?.Value;

N
Nikita, 2018-03-22
@Smiz001

You don't have a Value property because you always return a collection of XElements.
You either need to loop through this collection, or bypass it through LINQ and take the Value from the elements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question