解析XML属性时需先判断属性是否存在,避免NullReferenceException;2. 使用XElement.Attribute("name")获取可空XAttribute,判空后再取Value;3. 类型转换应采用int.TryParse等TryParse模式,防止FormatException;4. 可封装扩展方法统一处理null检查与类型转换,提升代码安全性与复用性。

在C#中解析XML时,经常需要读取元素的属性值。但若处理不当,很容易遇到数据类型转换异常或null值引发的运行时错误。关键在于正确判断属性是否存在,并安全地进行类型转换。
XML属性可能不存在,直接访问会导致NullReferenceException。应在获取前确认属性存在。
XElement.Attribute("name")返回XAttribute?(可空)Value
示例:
var attr = element.Attribute("count");
if (attr != null)
{
int count = int.Parse(attr.Value);
}即使属性存在,其值也可能不是期望的数据类型,如将"abc"转为int会抛出FormatException。应使用TryParse模式避免异常。
int.TryParse、double.TryParse等方法示例:
if (element.Attribute("price")?.Value is string priceStr &&
double.TryParse(priceStr, out double price))
{
// 使用price
}
else
{
price = 0; // 默认值
}可封装通用逻辑,简化重复代码。例如扩展方法:
public static bool TryGetAttributeValue(this XElement element, string attrName, out int value)
{
value = 0;
var attr = element?.Attribute(attrName);
return attr != null && int.TryParse(attr.Value, out value);
}调用时:
if (element.TryGetAttributeValue("age", out int age))
{
Console.WriteLine($"Age: {age}");
}基本上就这些。只要始终检查null并用TryParse处理转换,就能避免大多数XML属性解析问题。不复杂但容易忽略。
以上就是C#解析XML属性值失败? 数据类型转换与null值处理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号