【发布时间】: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 公平点 :),我没想到!