如何在xml和c#中处理null

时间:2011-05-02 10:18:12

标签: c# xml-serialization

假设我正在尝试将xml反序列化到我的类中,如果任何值为null或为decimal或datetime为空,那么如何处理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或为空,那么在反序列化时如何处理它。需要解决方案感谢。

4 个答案:

答案 0 :(得分:6)

您可以在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".

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

或者,您可以实现填充属性:

XML Deserialization of a date with an empty value

答案 3 :(得分:0)

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