2011-05-02 80 views
5

假设我试图将xml反序列化到我的类,如果任何值为空或为十进制或日期时间为空,那么如何处理null。如何在xml和c中处理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或为空,那么在反序列化时如何处理它。需要解决。谢谢。

回答

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

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

或者你可以实现一个垫片属性:

XML Deserialization of a date with an empty value

+0

什么是垫片财产两种选择。详细讨论。 – Mou 2011-05-02 11:52:31

2

。利用Nullabe类型会很容易解决的问题。

+0

如何为我的房产添加Nullabe类型。 plzz节目。 – Mou 2011-05-02 11:53:19

+0

@ user728750 - 像这样公开可空 Bar {get;组; } – 2011-05-02 11:56:28

0

您可以使用Microsoft企业库验证应用程序块。或者简单地将类型改为Nullable。