TAGS :Viewed: 5 - Published at: a few seconds ago

[ How to get integer/double value from XML ]

I'm trying to get stock data using YQL from Yahoo.

I have tried to use XML to accomplish this, but I have run into trouble getting integer values (I think I need to use double as prices are in decimals). Originally I was able to get string values, such as 'Currency', but I changed some code and can't get a return anymore.

I am trying to get the value from the node to display in a textbox (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;

I tried to use int.Parse("string") when trying to get double nodes... but I couldn't get it to work.

Any help would be appreciated, thanks.

Answer 1


I am not sure what your problem is, but this Linq2Xml code returns ,for ex, the Bid value correctly (Just cast the node to correct type)

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

PS: you will need

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

Answer 2


You should use field.InnerText, field.Value returns null in your case.

Here this code is working.

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

    }

If you want to take more than one note.

        XmlNodeList nodes = xmlDoc.SelectNodes("/query/results/quote/Name");

        foreach(XmlNode node in nodes)
        {
            if (node != null)
                Console.WriteLine(node.InnerText);
        }

If the values is integer/decimal you can convert to them from string !