0

I have the following link: XML File

as you can see it has an XML file with an object called currencies which holds a list of currency.

I have Currency class and I need to extract that list of "Currency" into an object "list<Currency> allCurrencies=...."

It is a UWP Project. preferably without async stuff, and I don't have for some reason a dll for the WebClient class. I tried a lot of ways but it always fails, with all sorts of exceptions.

Eden
  • 19
  • 4
  • there are some classes starting with XML that might help you: [XmlDocument](https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx) - if you dont know how to use them, search SO for `C# howto parse xml into class` - f,.e. this: [how-to-deserialize-xml-document](https://stackoverflow.com/questions/364253/how-to-deserialize-xml-document) – Patrick Artner Nov 12 '17 at 18:21
  • 2
    Possible duplicate of [How to Deserialize XML document](https://stackoverflow.com/questions/364253/how-to-deserialize-xml-document) – Patrick Artner Nov 12 '17 at 18:22
  • *I have Currency class and I need to extract that list of "Currency" into an object ..* -- the please [edit] your question to share what you have so far and where you are stuck. As it is see [Generate C# class from XML](https://stackoverflow.com/q/4203540/3744182) and [How to Deserialize XML document](https://stackoverflow.com/q/364253/3744182). – dbc Nov 12 '17 at 18:25

1 Answers1

1

Using XML Linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string URL = "http://www.boi.org.il/currency.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);

            Currency.currencies = doc.Descendants("CURRENCY").Select(x => new Currency() {
                name = (string)x.Element("NAME"),
                unit = (int)x.Element("UNIT"),
                code = (string)x.Element("CURRENCYCODE"),
                country = (string)x.Element("COUNTRY"),
                rate = (decimal)x.Element("RATE"),
                change = (decimal)x.Element("CHANGE")
            }).ToList();
        }
    }
    public class Currency
    {
        public static List<Currency> currencies = new List<Currency>();

        public string name { get; set; }
        public int unit { get; set; }
        public string code { get; set; }
        public string country { get; set; }
        public decimal rate { get; set; }
        public decimal change { get; set; }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • 1
    XDocument.Load() doesnt work with URL, it needs to be a file path. it threw an exception System.Xml.XmlException: 'Cannot open 'http://www.boi.org.il/currency.xml'. The Uri parameter must be a file system relative or absolute path.' – Eden Nov 13 '17 at 21:18