2011-05-02 77 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。