【问题标题】:How to handle null in xml and c#如何处理 xml 和 c# 中的 null
【发布时间】:2013-08-02 05:27:32
【问题描述】:

假设我正在尝试将 xml 反序列化到我的班级,如果任何值对于小数或日期时间为 null 或为空,那么如何处理 null。

[XmlElement(ElementName = "Salary" , typeof(double))]
public string Salary { get; set; }

[XmlElement(ElementName = "BirthDate" , typeof(DateTime))]
public string Phone { get; set; }

假设如果 BirthDate 或 Salary 在 xml 中为 null 或为空,那么在反序列化时如何处理它。需要解决方案。谢谢。

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    XmlSerializer Class 中指定了两个选项

    指定一个System.ComponentModel.DefaultValueAttribute来指定默认值

    [System.ComponentModel.DefaultValueAttribute ("0")]
    [XmlElement(ElementName = "Salary" , typeof(double))]
    public string Salary { get; set; }
    
    [System.ComponentModel.DefaultValueAttribute ("02-May-2011")]
    [XmlElement(ElementName = "BirthDate" , typeof(datetime))]
    public string Phone { get; set; }
    

    Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether or not to generate the XML element named "MyFirstName".

    【讨论】:

      【解决方案2】:

      使用 Nullabe 类型可以轻松解决问题。

      【讨论】:

      • @user728750 - 像这个 public Nullable Bar { get;放; }
      【解决方案3】:

      将“double”替换为可空类型等效的“double?”应该这样做。然后简单地处理对象中缺少值的问题。

      或者,您可以实现一个 shim 属性:

      XML Deserialization of a date with an empty value

      【讨论】:

      • 什么是 shim 属性。详细讨论。
      【解决方案4】:

      您可以使用 Microsoft Enterprise Library 验证应用程序块。或者干脆将类型更改为 Nullable。

      【讨论】:

        猜你喜欢
        • 2010-09-18
        • 2015-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        • 2011-05-25
        相关资源
        最近更新 更多