0

I need to be able to get the currency exchange rate from EUR => CHF for each day of a month. Therefor i got an XML Link from the gov.

The Link with the XML is this one.

Here's a snippet of the XML:

<devise code="eur">
  <land_de>Europäische Währungsunion</land_de>
  <land_fr>Union monétaire européenne</land_fr>
  <land_it>Unione Monetaria Europea</land_it>
  <land_en>Euro Member</land_en>
  <waehrung>1 EUR</waehrung>
  <kurs>1.05222</kurs>
</devise>
<devise code="gbp">
  <land_de>Grossbritannien</land_de>
  <land_fr>Grande-Bretagne</land_fr>
  <land_it>Gran Bretagna</land_it>
  <land_en>United Kingdom</land_en>
  <waehrung>1 GBP</waehrung>
  <kurs>1.48298</kurs>
</devise>

I need to get the value "1.05222" from the EUR node (which is the currency exchangerate).

I tried the following code, but it doesn't work, the result is always empty.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);

string kurs="";

XmlNodeList xnList = xmlDoc.SelectNodes("/wechselkurse/devise[@code='eur']");
foreach (XmlNode xn in xnList)
{
   kurs = xn["kurs"].InnerText;
}
1
  • @CharlesMager: guess my memory was rusty. Commented Aug 13, 2015 at 9:41

1 Answer 1

3

I wouldn't use the old XmlDocument API. Here's how you might do it using the cleaner LINQ to XML API:

XNamespace ns = "http://www.afd.admin.ch/publicdb/newdb/mwst_kurse";

var doc = XDocument.Load("http://www.afd.admin.ch/publicdb/newdb/mwst_kurse/wechselkurse.php?d=20150701");

var eur = doc.Descendants(ns + "devise")
    .Where(e => (string)e.Attribute("code") == "eur")
    .Select(e => (decimal)e.Element(ns + "kurs"))
    .Single();

Here's a working demo: https://dotnetfiddle.net/Iz6NHO

You can also use XPath (though the query methods are usually preferable due to the static typing). The only issue with your query is you need to account for the namespace:

var nsm = new XmlNamespaceManager(new NameTable());

nsm.AddNamespace("k", "http://www.afd.admin.ch/publicdb/newdb/mwst_kurse");

var eur = (decimal)doc.XPathSelectElement("/k:wechselkurse/k:devise[@code='eur']/k:kurs", nsm);    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.