我正在尝试从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);
}
我编辑了代码以查看输出,我什么都没得到。 我做错了什么?
提前致谢。
答案 0 :(得分:4)
@David Faiz It Works!
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"http://www.boi.org.il//currency.xml");
XmlNodeList xmllist = xDoc.GetElementsByTagName("CURRENCIES");
Console.WriteLine(xmllist.Count);
您必须在网址中添加//斜杠。这就是为什么你把'xmllist.Count'当作零。
答案 1 :(得分:1)
这是您的代码的快速重构..
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()方法一起使用。