J B*_*min 1 c# xml currency-exchange-rates
使用来自欧洲中央银行的此 URL:
www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
我想将货币符号和汇率导入到字典或对象中。我已经把它读入了一个 xml 文档,但我在挑选节点属性时遇到了麻烦。
谢谢
string xmlString;
using (var client = new WebClient())
{
xmlString = client.DownloadString("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
foreach(XmlNode node in xmlDoc.SelectNodes("//*/Cube/@currency"))
{
// add currency and rate to dictionary
}
Run Code Online (Sandbox Code Playgroud)
我认为问题出在您的 xPath 选择器上。
值"//*[@currency]"将选择具有“货币”属性的所有元素
class Program
{
public static void Main(string[] args)
{
List<Rate> rates = new List<Rate>();
var doc = new XmlDocument();
doc.Load(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
XmlNodeList nodes = doc.SelectNodes("//*[@currency]");
if (nodes != null)
{
foreach (XmlNode node in nodes)
{
var rate = new Rate()
{
Currency = node.Attributes["currency"].Value,
Value = Decimal.Parse(node.Attributes["rate"].Value, NumberStyles.Any, new CultureInfo("en-Us"))
};
rates.Add(rate);
}
}
}
}
class Rate
{
public string Currency { get; set; }
public decimal Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1401 次 |
| 最近记录: |