【问题标题】:How to get integer/double value from XML如何从 XML 获取整数/双精度值
【发布时间】:2014-11-29 15:04:03
【问题描述】:

我正在尝试使用 Yahoo 的 YQL 获取股票数据。

我尝试使用 XML 来完成此操作,但在获取整数值时遇到了麻烦(我认为我需要使用双精度值,因为价格是小数)。本来我可以得到字符串值,比如'Currency',但是我改变了一些代码,再也不能得到返回了。

我正在尝试从节点获取值以显示在文本框 (tbValue) 中;

string url = @"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&env=store://datatables.org/alltableswithkeys";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url)

XmlNode field = xmlDoc.SelectSingleNode("/query/results/quote/Name");
string desiredValue = "";
if (field != null ) desiredValue = field.Value;
MessageBox.Show(desiredValue);
tbValue.Text = ptest;

我在尝试获取双节点时尝试使用 int.Parse("string") ......但我无法让它工作。

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: c# xml visual-studio stocks


    【解决方案1】:

    您应该使用field.InnerTextfield.Value 在您的情况下返回 null。

    这里的代码是有效的。

        static void Main(string[] args)
        {
    
            //Error Trapping
            string url = @"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&env=store://datatables.org/alltableswithkeys";
    
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(url);
    
    
            XmlNode field = xmlDoc.SelectSingleNode("/query/results/quote/Name");
            string desiredValue = "";
            if (field != null ) 
                desiredValue = field.InnerText;
    
            Console.WriteLine(desiredValue);
    
        }
    

    如果你想记多个笔记。

            XmlNodeList nodes = xmlDoc.SelectNodes("/query/results/quote/Name");
    
            foreach(XmlNode node in nodes)
            {
                if (node != null)
                    Console.WriteLine(node.InnerText);
            }
    

    如果值是整数/十进制,您可以从字符串转换为它们!

    【讨论】:

    • 太好了。我相信 InnerText 将值作为字符串引入,即使它是 int/decimal,所以不需要转换 :) 感谢您的帮助。
    • @adventuresncode 欢迎您,祝您的项目或作业好运 :)
    【解决方案2】:

    我不确定你的问题是什么,但是这个 Linq2Xml 代码正确返回了 Bid 值 (只需将节点转换为正确的类型

    var xDoc = XDocument.Load(url);
    var bid = (decimal)xDoc.XPathSelectElement("/query/results/quote/Bid");
    

    PS:你需要

    using System.Xml.XPath;
    using System.Xml.Linq;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多