我有以下要反序列化的 XML 代码:
<a>
<b> n/a </b>
</a>
现在 b 通常是一个整数,但有时 "n/a"表示不可用。每当我反序列化上述 XML 时,我都会收到一个异常,指出我使用了错误的格式……什么是正确的。 但我需要 int 只是一个空值
public class a
{
Nullable<int> b;
}
最佳答案
你能做到的唯一方法是使用类似的东西:
[XmlIgnore]
public int? B {get;set;}
public bool ShouldSerializeBSerialized() {
return B.HasValue;
}
[XmlElement("b")]
public string BSerialized {
get { return B.ToString(); }
set {
int tmp;
if(value != null && int.TryParse(value.Trim(), out tmp))
{
B = tmp;
}
}
}
这里:
B
是int?
我们将用来存储数据BSerialized
是处理解析等的 shim 属性ShouldSerializeBSerialized
确保我们只序列化有效数据
关于c# - 在 C# 中反序列化 XML - 格式错误时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6409533/