简体   繁体   中英

Cannot convert string to int. Data from an XML element. C#

I'm having an unusual problem. I'm a bit of a beginner, but I'm trying to learn how to extract info from an XML document. I've done it before with no problems, but I'm having trouble now. Here's what happens:

I attempt to extract the latitude value from the following XML:

<ip2locationapi>
  <countryCode>GB</countryCode> 
  <countryName>United Kingdom</countryName> 
  <region>Wales</region> 
  <city>Cardiff</city> 
  <latitude>51.5</latitude> 
  <longitude>-3.2</longitude> 
</ip2locationapi>

by using the following code:

var latitude = from r in document.Descendants("ip2locationapi")
               select new
               {
                   lati = r.Element("latitude").Value,
               };      

foreach (var item in latitude)
{
    Convert.ToInt32(item.lati);
}

But doing this gives me an exception, telling me I can't convert as it's in the wrong format.

Does anyone know what I might be doing wrong?

Obviously 51.5 is not an integer, it's a floating point value. Use Convert.ToDouble instead.

As BartoszKP pointed out, 51.5 is not an int, so your question is a bit difficult for us to figure out what you're trying to do.

That said, maybe this can get you going...

var e = document.Descendants("latitude").FirstOrDefault();

double d = 0;
int i = 0;

if(double.TryParse(e.Value, out d))
    i = (int)d;
else
    Console.WriteLine("{0} is not valid.", e.Value);

Console.WriteLine("{0} is a double.", d);
Console.WriteLine("{0} is a an int.", i);

Keep in mind that the cast (int)d will not throw an exception if the value of d is outside the range of an int - ie If d = 2147483648 (which is greater than the max value of an int ), the resultant cast will be -2147483648

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM