如何在xml和c#中处理null

Mou*_*Mou 5 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; }
Run Code Online (Sandbox Code Playgroud)

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

Waq*_*aja 6

您有两个在XmlSerializer类中指定的选项

指定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; }
Run Code Online (Sandbox Code Playgroud)

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".