Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null in xml and c#

suppose i am trying to deserialize xml to my class and if any value is null or empty for decimal or datetime then how to handle the null.

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

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

suppose if BirthDate or Salary is null or empty in xml then how to handle it at the time of deserialization. need solution. thanks.

like image 273
Mou Avatar asked May 02 '11 10:05

Mou


People also ask

How does XML handle null values?

In an XML document, the usual way to represent a null value is to leave the element or attribute empty. Some business messages use a special value to represent a null value: <price>-999</price> . This style of null representation is supported by the DFDL and MRM parsers.

Can XML have empty tags?

Empty XML ElementsAn element with no content is said to be empty. The two forms produce identical results in XML software (Readers, Parsers, Browsers). Empty elements can have attributes.

How do you pass null in SOAP request?

How can I set a field as null using the SOAP API? Notice the xsi:nil="true" on the <ns2:DataValue> tag. This tells the SOAP envelope to make this field as "NULL". Now the SOAP request should process without issue.

How do you write empty text in XML?

In your message action (e.g. Publish) right click the "text (String) {XML}" node and select "Properties". Clear the check box "Send NULL values". Your message action should now include an empty string as the node value.


2 Answers

You have two options as specified here in XmlSerializer Class

Specify a System.ComponentModel.DefaultValueAttribute to specify the default value

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

like image 156
Waqas Raja Avatar answered Sep 23 '22 00:09

Waqas Raja


Make use of Nullabe type will resolve issue easily.

like image 26
Pranay Rana Avatar answered Sep 23 '22 00:09

Pranay Rana