Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML serialization and DefaultValue("") related problem in c#

my class property has default value which will be serialize.

public class DeclaredValue
{
    [XmlElement(ElementName = "Amount", DataType = "double", IsNullable = false), DefaultValue(999)]
    public double Amount { get; set; }

    [XmlElement(ElementName = "Reference2", DataType = "string", IsNullable = false), DefaultValue("")]
    public string Reference2 { get; set; }
}

so we create instance of DeclaredValue class and provide value for Reference2 property and do not assign anything for Amount. so when we serialize the class DeclaredValue then no tag found for amount in my xml. i mention default value for amount "999" then why it does not work in serialization. i want that if do not assign anything for amount then amoun tag should be there in my xml with default value.

to do this what way i need to decorate the amount property that it always comes with default value in xml after serialization if user do not assign anything to this property.

please guide me what i need to change in the code to get my desired output.

like image 520
Mou Avatar asked May 04 '11 10:05

Mou


People also ask

What is XML serialization and Deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.

What occasions the XML serialization throws an exception?

XmlSerializer throws exception when the type belongs to an assembly with no location property set #24614.

What is XML serialization?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is the basic difference between soap Serialisation and XML Serialisation?

- SoapFormatter is better to serialize arbitrary data. - XML Serialization would just serialize the public properties of an object. - The XML Serializer is used typically for serializing simple types across web services. - Xmlserializer is better, more flexible and faster.


1 Answers

Per the note on MSDN:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

Somewhat surprisingly the DefaultValue only regulates the writing of an object, members that are equal to their DefaultValue will not be written out.

You must still initialize members before or after loading yourself, for example in the constructor.

like image 154
Henk Holterman Avatar answered Nov 10 '22 01:11

Henk Holterman