[英]Not sure how to deal with none-fixed XML data types
我正在读取XML文件,并使用其中的数据创建新对象,然后使用LINQ使用读取的数据设置对象属性。
例如,XML的一部分如下所示:
<heat_index_string>NA</heat_index_string>
<heat_index_f>NA</heat_index_f>
<heat_index_c>NA</heat_index_c>
<windchill_string>NA</windchill_string>
<windchill_f>NA</windchill_f>
<windchill_c>NA</windchill_c>
<pressure_mb>1013</pressure_mb>
<pressure_in>29.92</pressure_in>
通常,这些“NA”的将由一个代表double
(EG: public double HeatIndexC { get; set; }
但是,如果这些数据是无法从该服务,则服务回报‘NA’。 XML的其他地方没有其他信息可提供可用或不可用的数据列表。
我这样阅读XML:
var data = from i in weather.Descendants("current_observation")
select new CurrentConditions
{
HeatIndexC = (double)i.Element("heat_index_c"),
//Set other properties here
};
可以看出,只要服务返回双精度值,它就可以正常工作,但是一旦返回字符串,则将导致异常。
那么,我该如何处理呢? 我的第一个想法是为每个部分创建更多属性,如下所示:
public bool TemperatureAvaliable { get; set; };
我的另一个想法是只使用字符串类型,但这似乎很不灵活,一点也不习惯。
需要说明的是:我不知道如何处理有时返回双精度值但有时还会返回字符串的服务。 此外,该服务未声明何时返回字符串或双精度型。
而不是强制转换为double,请使用TryParse
。
如果heatIndex没有解析,我假定默认值为0。 使用可为null的double可能是更合适的选择。
double heatIndexC;
var data = from i in weather.Descendants("current_observation")
select new CurrentConditions
{
var HeatIndexC = double.TryParse(i.Element("heat_index_c")
.Value, out heatIndexC)
? heatIndexC : 0,
//Set other properties here
};
编辑:固定值的输出。
我会使用Nullable<double>
(aka double?
)。 那么问题是:如何将“ NA”转换为double?
? 这是一种方法:
var data = from i in weather.Descendants("current_observation")
select new CurrentConditions
{
HeatIndexC = ToNullableDouble(i.Element("heat_index_c")),
//Set other properties here
};
double? ToNullableDouble(object xml)
{
if (xml == null)
return null;
if (xml is double)
return (double?)xml;
double value;
return double.TryParse(xml.ToString(), out value) ? value : (double?)null;
}
您可能还希望显式查找“ NA”,然后在出现任何无法识别的字符串时引发异常,而不是静默删除意外数据。
编辑
我刚刚注意到XElement也定义了此转换运算符,这可能是处理此问题的更好方法:
var data = from i in weather.Descendants("current_observation")
select new CurrentConditions
{
HeatIndexC = (double?)i.Element("heat_index_c"),
//Set other properties here
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.