我正在嘗試從URL中讀取XML文件。
URL和文件都很好,它們持有貨幣匯率。從URL讀取XML文件,出現空
10次運行代碼9時,沒有內容返回。
下面是代碼:
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);
}
我已編輯的代碼,看看輸出,我什麼也沒得到。 我在做什麼錯?
在此先感謝。
你正在做你不需要的'foreach'中的轉換。你根本不需要「foreach」或匿名類型。我得到數據10/10次我打了服務,我不知道你爲什麼不會 – Jonesopolis
同上...我正在運行它,只是打印出名字和國家......每次都有效。有沒有例外,或者你有其他代碼,使它看起來像這個代碼沒有運行?另外@Jonesy說...不需要轉換兩次。 – Kevin
嗯..數據變量的要點是什麼? doc.Elements包含XElements ..所以它應該只是foreach(XElement elm in doc) –