c# - 在 C# 中反序列化 XML - 格式错误时返回 null

标签 c# xml serialization

我有以下要反序列化的 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;
       }
    }
}

这里:

  • Bint? 我们将用来存储数据
  • BSerialized 是处理解析等的 shim 属性
  • ShouldSerializeBSerialized 确保我们只序列化有效数据

关于c# - 在 C# 中反序列化 XML - 格式错误时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6409533/

相关文章:

c# - 从 proto 文件构建 cs 文件?

android - 在android中通过ant脚本更改应用程序名称

XML Odoo 字段条件颜色格式

c# - 使用 JSON.NET 序列化对象的动态属性名称

c# - WPF 自定义用户控件 - "The member X is not recognized or accessible"

C#;在不单独声明方法的情况下创建一个新委托(delegate)?

C# 排序 Arraylist 字符串按字母顺序和长度

xml - Log4net xml appender 不创建根元素

c++ - C++ 的 YAML 序列化库?

C#序列化