【发布时间】:2014-09-17 17:29:39
【问题描述】:
我正在尝试从 URL 读取 XML 文件。
URL 和文件很好,它们包含货币汇率。
当代码运行 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 次服务的数据,我不知道你为什么不这样做 -
同上...我正在运行它,只是打印出名称和国家...每次都有效。是否存在异常,或者您可能有其他代码使该代码看起来没有运行?同样正如@Jonesy 所说......无需转换两次。
-
hmm.. 数据变量的意义何在? doc.Elements 由 XElements 组成.. 所以它应该只是 foreach (XElement elm in doc)
-
我没有删除 XMLReader 标记引用.. 但我没有看到它在此代码中使用.. Reader 对象通常使用流.. 负载中肯定存在流() 方法..但它不在你这里的使用范围内..
-
@BrettCaswell,我对我的代码进行了一些编辑,但仍然一无所获。打开一个新项目,仍然没有。可以是某种 cookie 吗?
标签: c# xml linq-to-xml xmlreader