我正在使用 LINQ 和 XDocument 来解析 XML 文件。 XML 中的某些字段不是固定的,因为它们有时可能是 double 型或字符串型。通常它是一个 double ,但一个字符串将指示数据不可用。
例如:
<current_observation>
<temp_c>12.1</temp_c>
<temp_c>NA</temp_c>
</current_observation>
我读入 XML 字段,然后在新对象实例中设置属性。像这样:
var data = from i in weatherResponse.Descendants("current_observation")
select new CurrentConditions
{
// Attempt to parse. Set to null if not a double.
// This is one of the areas I'm having trouble with.
TemperatureC = Utilities.ParseDoubleValue(i.Element("temp_c"))
// If I use the following line instead then it works without problem.
// But this misses out all of the safe parsing.
// TemperatureC = (double)i.Element("temp_c")
};
我决定使用 Nullable 类型,这样我就可以使用 TryParse 将字段解析为 double,或者如果这不可能,则将属性设置为一个空值。
这是我用来尝试解析该字段的代码:
public static class Utilities
{
public static double? ParseDoubleValue(object inputValue)
{
if (inputValue == null)
return null;
double returnValue;
return double.TryParse(inputValue.ToString(), out returnValue) ? returnValue : (double?)null;
}
}
但是,似乎在我的代码中某处它实际上并没有正确解析该字段,因为如果我这样做:
if(currentConditions.TemperatureC.HasValue)
Console.WriteLine("Has a value: {0}", currentConditions.TemperatureC.Value);
else
Console.WriteLine("Not Avaliable.");
然后 HasValue 将始终返回 false。
我的问题:为什么我尝试解析值的方法不起作用?我是否误解了 TryParse 和可空类型的用法?
请您参考如下方法:
XElement定义 explicit type conversions到各种数字类型。因此,(double)i.Element("temp_c")被允许并转换 value的 XElement为 double 据类型(通过内部调用 Double.Parse )。
当 XElement作为 object 类型的参数传递给你的Utilities.ParseDoubleValue方法,你正在传递整个 XElement .调用inputValue.ToString()不返回 12.1 ,而是 <temp_c>12.1</temp_c> , the indented XML value for the node .和 double.TryParse("<temp_c>12.1</temp_c>")当然会失败。
错误在于您很可能想为该方法提供 XElement 的字符串值,而不是 XElement 本身。这是一个简单的更改问题:
TemperatureC = Utilities.ParseDoubleValue(i.Element("temp_c"))
到
TemperatureC = Utilities.ParseDoubleValue(i.Element("temp_c").Value)
其次,作为防御措施,您可能需要重新考虑方法的方法签名:
public static double? ParseDoubleValue(object inputValue)
这将接受任何对象,但您最终感兴趣的是转换调用者提供的字符串。将其更改为仅接受一个字符串将确保调用者提供一个字符串,否则将导致编译错误。
public static double? ParseDoubleValue(string inputValue)
