【问题标题】:Cannot convert string to int. Data from an XML element. C#无法将字符串转换为 int。来自 XML 元素的数据。 C#
【发布时间】:2013-11-15 16:41:30
【问题描述】:

我遇到了一个不寻常的问题。我有点初学者,但我正在尝试学习如何从 XML 文档中提取信息。我以前做过,没有问题,但我现在遇到了麻烦。以下是发生的事情:

我尝试从以下 XML 中提取 latitude 值:

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

使用以下代码:

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

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

但是这样做给了我一个例外,告诉我我无法转换,因为它的格式错误。

有人知道我做错了什么吗?

【问题讨论】:

  • 如果您想将其保留为整数,请尝试 Convert.ToInt32(Convert.ToDouble(item.lati));。否则做 Convert.ToDouble。
  • @MPatel 不需要为此调用Converter 的东西。 (int)Convert.ToDouble(item.lati) 就够了。
  • @BartoszKP 公平点 :),我没想到!

标签: c# .net xml parsing int


【解决方案1】:

显然51.5 不是整数,而是浮点值。请改用Convert.ToDouble

【讨论】:

    【解决方案2】:

    正如 BartoszKP 指出的那样,51.5 不是 int,所以你的问题对我们来说有点难以弄清楚你想要做什么。

    也就是说,也许这可以让你继续......

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

    请记住,如果d 的值超出int 的范围,则强制转换(int)d 不会引发异常——即如果d = 2147483648(大于@ 的最大值) 987654327@),结果转换为-2147483648

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2013-04-03
      • 2018-05-10
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      相关资源
      最近更新 更多