Я пытаюсь прочитать XML файл из URL-адреса.
URL и файл в порядке, они поддерживают курсы валют.
При запуске кода 9 из 10 раз содержимое не возвращается.
Вот код:
XDocument doc = XDocument.Load("http://www.boi.org.il/currency.xml");
int currID = 0;
Dictionary<int, Currency> curr; // declares the dictionary
curr = new Dictionary<int, Currency>();
var data = from item in doc.Descendants("CURRENCY") // LINQ the informartion from the xml to data variable
select new
{
name = item.Element("NAME").Value,
country = item.Element("COUNTRY").Value,
currencyCode = item.Element("CURRENCYCODE").Value,
rate = Convert.ToDouble(item.Element("RATE").Value),
unit = Convert.ToDouble(item.Element("UNIT").Value),
change = Convert.ToDouble(item.Element("CHANGE").Value),
};
foreach (var xn in data) // run in foreach on the data that we read from the xml and put it in a currency variable into the dictionary
{
Currency currency = new Currency();
currency.Name = xn.name;
currency.Country = xn.country;
currency.CurrencyCode = xn.currencyCode;
currency.Rate = Convert.ToDouble(xn.rate);
currency.Unit = Convert.ToDouble(xn.unit);
currency.Change = Convert.ToDouble(xn.change);
curr.Add(currID, currency);
currID++;
}
foreach (KeyValuePair<int, Currency> entry in curr)
{
Console.WriteLine(entry.Value.CurrencyCode);
}
Я редактировал код, чтобы увидеть результат, я ничего не получаю. Что я делаю не так?
Заранее спасибо.
@Давид Файз работает!
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"http://www.boi.org.il//currency.xml");
XmlNodeList xmllist = xDoc.GetElementsByTagName("CURRENCIES");
Console.WriteLine(xmllist.Count);
Вы должны добавить//слэши в URL. Вот почему u получил "xmllist.Count" как Zero.
Вот быстрый рефактор вашего кода..
XDocument doc = XDocument.Load(@"http://www.boi.org.il/currency.xml");
foreach (XElement elm in doc.Elements)
{
Currency currency = new Currency();
currency.Name = elm.Element("NAME").Value;
currency.Country = elm.Element("COUNTRY").Value;
currency.CurrencyCode = elm.Element("CURRENCYCODE").Value;
currency.Rate = Convert.ToDouble(elm.Element("RATE").Value);
currency.Unit = Convert.ToDouble(elm.Element("UNIT").Value);
currency.Change = Convert.ToDouble(elm.Element("CHANGE").Value);
MessageBox.Show(elm.Element("CURRENCYCODE").Value);
curr.Add(currID, currency);
currID++;
}
Однако я не уверен, что это касается основной проблемы, с которой вы сталкиваетесь.
Вы можете включить пространство имен System.Net и инициализировать объект XMLHttpRequest и использовать поток Response со статическим методом XDocument.Load().
foreach
которые вам не нужны. Вам действительно не нуженforeach
или анонимный тип вообще. Я получаю данные 10/10 раз, когда обращаюсь в службу, я понятия не имею, почему бы вам не