Title: Get currency exchange rates in C#
This example shows how you can get currency exchange rates from finance.yahoo.com. When it starts, the program uses the following code to get the currency exchange rates.
// Get the currency symbols.
private void Form1_Load(object sender, EventArgs e)
string url = "http://finance.yahoo.com/webservice/" +
// Load the data.
XmlDocument doc = new XmlDocument();
// Process the resource nodes.
XmlNode root = doc.DocumentElement;
string xquery = "descendant::resource[@classname='Quote']";
foreach (XmlNode node in root.SelectNodes(xquery))
const string name_query =
const string price_query =
string name =
string price =
decimal inverse = 1m / decimal.Parse(price);
ListViewItem item = lvwPrices.Items.Add(name);
lvwPrices.Sorting = SortOrder.Ascending;
lvwPrices.FullRowSelect = true;
catch (Exception ex)
MessageBox.Show(ex.Message, "Read Error",
This code loads an XmlDocument from the following url.
You can execute this URL in your browser to see what the result looks like. The following text shows what an entry that holds currency exchange rates looks like.
Next the code finds the document's root node and uses its SelectNodes method to make a list of nodes that have the tag type resource and that have a field named classname with value Quote. The program uses a while loop to iterate through the resulting nodes.
Inside the loop, the code gets the Quote node's descendants of type field with name name and price. It saves their text contents in variables name and price.
I think the names of the currency exchange rates are a bit misleading. For example, USD/JPY is the exchange rate between US dollars and Japanese yen. Currently the price is 114.528, which means one USD is worth 114.528 JPY. But mathematically the name USD/JPY means "dollars per yen" not "yen per dollar."
To make the exchanges a bit easier to read, the program parses the price and inverts it so you can see the number of dollars per yen and the number of yen per dollar.
The loop displays the name, price, and inverted price in the ListView control lvwPrices.
The code finishes by sorting the ListView values (they are not sorted in the XML data) and making the ListView select full rows when you click on it.
|Note that URL used by this example no longer works. The basic approach should work, but you'll need to find a new URL to download this data.
Download the example to experiment with it and to see additional details.