Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to avoid the XmlSerializer to not initialize a null property when deserializing?

I have this class:

public class MySerializableClass
{
    public List<MyObject> MyList { get; set; }
}

If MyList is null when MySerializableClass is serialized, I need to have it null when it's deserialised too, but the XmlSerializer always initializes it when it deserialises my class.

Is there a way to avoid it initializing null properties?

MyList is not even recorded in the serialized file when it's null. When I load it with null values, and save it again, MyList is not null anymore, it's serialized as a List<> with 0 items, but not null.

Thanks.

More info:

An IsDeserializing property is not viable due to some code restrictions in the structure of the class

like image 314
Carlo Avatar asked Feb 02 '10 23:02

Carlo


People also ask

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.

What is the correct way of using XML deserialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.


1 Answers

This looks like a bug...

Even if you try to mark the property as nullable, it doesn't seem to work.

[XmlArray(IsNullable = true)]
public List<MyObject> MyList { get; set; }

It serializes the MyList property as follows :

<MyList xsi:nil="true" />

So the XML clearly indicates that the list is null, but after deserialization, it is still initialized to an empty list...

If you replace List<MyObject> with MyObject[], it works fine (even without IsNullable = true), but it's probably not what you want...

You should probably report this on Connect.

like image 81
Thomas Levesque Avatar answered Nov 03 '22 07:11

Thomas Levesque