2014-10-04 37 views
0

我试图从雅虎获取使用YQL的股票数据。如何从XML获取整数/双精度值

我试图使用XML来完成这一点,但我得到整数值时遇到了麻烦(我想我需要使用双精度,因为价格是小数)。最初我能够获得字符串值,例如'货币',但是我改变了一些代码并且无法再获得回报。

我想从节点中获取值以显示在文本框(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(“字符串”)......但我无法让它工作。

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

回答

1

你应该使用field.InnerTextfield.Value回报你的情况为空。

此代码正在工作。

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

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

+0

太好了。我相信InnerText作为一个字符串带来的价值,即使它是一个int /小数,所以不需要转换:)感谢您的帮助。 – adventuresncode 2014-10-04 23:00:21

+0

@adventuresncode欢迎您,祝你的项目或任务顺利:) – mybirthname 2014-10-04 23:01:30

1

我不知道你的问题是什么,但这个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;