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

半腔热情 提交于 2019-11-27 17:59:16

问题


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


回答1:


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.




回答2:


Don't use Auto-Implemented Properties if you need a null there. use e.g.

public class MySerializableClass 
{ 
    List<MyObject> myList 
    public List<MyObject> MyList { get {return myList;} set {myList = value;} } 
} 



回答3:


I had the same problem but adding the XmlArrayAttribute to the property with nothing set made it work for me

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



回答4:


If you add a property with the name *PropertyName*Specified as a boolean the XmlSerializer will render the tag for the list only when it is true.

Example:

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

    [XmlIgnore]
    public bool MyListSpecified { get; set; }
}


来源:https://stackoverflow.com/questions/2188619/is-there-a-way-to-avoid-the-xmlserializer-to-not-initialize-a-null-property-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!