Reputation: 2163
This specific url <-- (click to view) is working fine.
http://bankisrael.gov.il/currency.xml
But when trying to read from it to extract currency, this is what I get no matter which way I try to tackle it ...
<html><body><script>document.cookie='iiiiiii=e0076bcciiiiiii_e0076bcc; path=/';window.location.href=window.location.href;</script></body></html>
Tried following :
using (WebClient c = new WebClient())
{
var result = c.DownloadString(@"http://bankisrael.gov.il/currency.xml");
}
Tried with above WebClient
... but not as first try.
This next code was my first try. What am I doing wrong ?
While "surfing" to the URL above, the XML is there. I would like to try with your help first before desperately I could think of another way.
I would be able to save the file to my hard drive (programmatically), then read it from the hdd. For that approach I didn't test yet, though I am sure it will work.
But I was trying to check with some experienced developers to have a try on this. What could be wrong?
string DollarURL = "http://bankisrael.gov.il/currency.xml";
xx.Load(DollarURL);
XmlNode root = xx;
Upvotes: 1
Views: 216
Reputation: 2128
There is a simpler way to access XML nodes with XPath:
using System;
using System.Net;
using System.Xml;
using System.Globalization;
// ...
using (WebClient c = new WebClient())
{
string result = c.DownloadString(@"http://bankisrael.gov.il/currency.xml");
CultureInfo culture = new CultureInfo("en-US");
XmlDocument xml = new XmlDocument();
xml.LoadXml(result);
foreach (XmlNode currency in xml.SelectNodes("/CURRENCIES/CURRENCY"))
{
string name = currency.SelectSingleNode("NAME").InnerText;
int unit = int.Parse(currency.SelectSingleNode("UNIT").InnerText);
string currencyCode = currency.SelectSingleNode("CURRENCYCODE").InnerText;
string country = currency.SelectSingleNode("COUNTRY").InnerText;
double rate = double.Parse(currency.SelectSingleNode("RATE").InnerText, culture);
double change = double.Parse(currency.SelectSingleNode("CHANGE").InnerText, culture);
Console.WriteLine("{2} {0} ({3}, {5}) rate:{1} change:{4}", currencyCode, rate, unit, country, change, name);
}
}
Upvotes: 0
Reputation: 102753
It looks like you should be using Linq to XML for this. Try XDocument.Load
:
var xdoc = XDocument.Load(DollarURL);
Now xdoc.Root
will give you the CURRENCIES
element:
Console.WriteLine(xdoc.Root.Name.LocalName); // "CURRENCIES"
Use xdoc.Root.Elements("CURRENCY")
to get all the currency nodes. Use xdoc.Save("filename")
to save to hard drive.
To query a certain currency, write it like this:
XElement[] usdElements = xdoc.Root.Elements("CURRENCY")
.Where(currency => (string)currency.Element("CURRENCYCODE") == "USD")
.ToArray();
For more info, read up on LINQ to XML on MSDN.
Upvotes: 2