How to use Yahoo! Query Language with C#

Yahoo Query

What is the Yahoo! Query Language?

“The Yahoo! Query Language is an expressive SQL-like language that lets you query, filter, and join data across Web services.” Source Yahoo!     Yahoo! is a huge database, and we can consume all these data with a very simple query. The data can be financial data, amazon content, geographical information, weather forecast… Well, you can get almost anything from Yahoo, and if you don’t find what you’re looking for, you can still create your own table and share it with the community.

Where to get the information?

Yahoo offers an excellent tool on the Yahoo! Developer Network, the Yahoo! Query Language console. From this interface, you can see the list of tables available, try them before using them in your applications.Yahoo Query Console

On the picture above, I show you how to get the forecast of the zip code 94123 (San Francisco, CA). The result is an XML file that you can easily parse with C#. You can also get the result in JSON format.

How to use it with C#?

Let’s try to display the list of counties in a state. I’ll use the table geo.counties. The example for this table is: select * from geo.counties where place=”CA” and return the list of the 57 counties in California. You see that you can easily change the state by replacing “CA” in the query by another state like “NY” for New York. The interface gives you the REST URL to call to retrieve all the information.

private static void RetrieveCounties(string state)
    // Create the Query URL
    string url = string.Format(BASE_URL, state);

    // Load the document from the URL
    XDocument doc = XDocument.Load(url);

    // The XML contains this namespace
    // we need to specify it in order to be able to parse the xml
    XNamespace xNamespace = "";

    // Retrieve the list of counties
    var xPlaces = doc.Root.Element("results").Elements(xNamespace + "place");
    foreach (var xPlace in xPlaces)
        // Display the element name
        Console.WriteLine(xPlace.Element(xNamespace + "name").Value);

To make the code easier to read / understand, I did not include any caching of exception…
Yahoo Query result

Leave a Reply