使用System.XElement获取汇率XML时规避NotFound错误并跳过异常日期
解决TCMB汇率数据获取时跳过无数据日期的问题
原代码在请求土耳其央行(TCMB)的汇率XML文件时,遇到公共假日等无对应XML文件的日期会触发NotFound异常,导致程序中断。同时原代码还存在一个小问题:判断当天日期时赋值的today.xmlURL会被后续语句覆盖,永远不会生效。下面是修复并添加异常处理后的代码:
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Xml.Linq; void SaveKurByDayAsync(DateTime firstDay, DateTime lastDay) { List<DateTime> dateList = new(); for (DateTime date = firstDay; date <= lastDay; date = date.AddDays(1)) { dateList.Add(date); } foreach (DateTime date in dateList) { // 直接用格式字符串生成两位的月/日,简化补零逻辑 string day = date.Day.ToString("D2"); string year = date.Year.ToString(); string month = date.Month.ToString("D2"); // 修复原代码中today URL被覆盖的问题,用Date属性避免时分秒干扰 string format; if (date.Date == DateTime.Today.Date) format = "https://www.tcmb.gov.tr/kurlar/today.xml"; else format = $"https://www.tcmb.gov.tr/kurlar/{year}{month}/{day}{month}{year}.xml"; try { List<XElement> exchangeList = XElement.Load(format).Elements().ToList(); foreach (XElement exchangeItem in exchangeList) { // 用TryParse替代直接Parse,避免节点值为空或格式错误时抛出异常 if (exchangeItem.Element("ForexBuying") is not null && decimal.TryParse(exchangeItem.Element("ForexBuying").Value, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal forexBuying)) { Console.WriteLine(forexBuying); } } } // .NET Framework环境捕获WebException判断404 catch (WebException ex) when (((HttpWebResponse)ex.Response)?.StatusCode == HttpStatusCode.NotFound) // .NET Core/.NET 5+环境请替换为下面的捕获语句: // catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { Console.WriteLine($"日期 {date:yyyy-MM-dd} 无汇率数据,跳过处理"); continue; } catch (Exception ex) { Console.WriteLine($"处理日期 {date:yyyy-MM-dd} 时发生未知错误:{ex.Message}"); continue; } } }
关键改动说明:
- 修复URL赋值逻辑:用
if-else分支正确区分当日和历史日期的URL,避免原代码中today.xml被覆盖的问题,同时用Date属性比较日期(排除时分秒干扰)。 - 简化日期格式化:用
ToString("D2")直接生成两位的月/日字符串,替代原代码中先转字符串再判断补零的冗余逻辑。 - 添加异常处理:针对404 NotFound异常做单独捕获,明确提示该日期无数据并跳过;同时捕获其他未知异常,输出错误信息后继续处理后续日期,避免程序整体中断。
- 增强解析安全性:用
decimal.TryParse替代直接decimal.Parse,避免XML中ForexBuying节点为空或格式错误时抛出异常。
内容的提问来源于stack exchange,提问作者Hakan Kaban
相关产品推荐
相关产品推荐

