【问题标题】:Having trouble performing multiplication on data from xml对来自 xml 的数据执行乘法时遇到问题
【发布时间】:2012-07-18 12:52:30
【问题描述】:

您好,我在乘以从 google 财务 api 检索到的数据时遇到问题。我知道我现在做的事情是错误的,所以我想要一些关于如何去做的指示以及一些关于这方面的例子。

    string url = "http://www.google.com/ig/api?stock=" + Server.UrlEncode(symbol1.Text);
     XmlDocument xdoc = new XmlDocument();
     xdoc.Load(url);
     currentPrice1.Text = GetData(xdoc, "last");
     int quantity = 50;
     int currentPrice = int.Parse(currentPrice1.Text);
     int totalValue = quantity * currentPrice;

GetData 方法

private string GetData(XmlDocument doc2, string strElement)
{

    XmlNodeList xnodelist5 = doc2.GetElementsByTagName(strElement);
    XmlNode xnode5 = xnodelist5.Item(0);
    return Get_Attribute_Value(xnode5, "data");

}

错误

【问题讨论】:

  • 乘法时请告诉我们错误
  • 是的,我补充说谢谢你提醒我!

标签: c# asp.net xml google-api xmldocument


【解决方案1】:

可能是 data 属性的值不是数字或未指定。使用 TryParse 方法或使用 try..catch.. 块包装您的代码。

 decimal currentPrice;
 if(decimal.TryParse(currentPrice1.Text, out currentPrice))
  {
     //
   }

如果数据属性的值为整数,则使用int.TryParse

【讨论】:

  • 谢谢你,你是一个救生员。数据属性为十进制。
【解决方案2】:

查看代码curentPrice1.Text 的打印屏幕可能有一个null、空或一些非数字

所以请这样做

int currentPrice = 0;

if(!string.IsEmptyOrNull(currentPrice1.Text))
{
   int price = 0;
   if(int.TryParse(currentPrice1.Text, out price))
   {
       currentPrice = price ;
   }
}

【讨论】:

    猜你喜欢
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    相关资源
    最近更新 更多