views:

31

answers:

2

I have a handful of public read/write members that are not being serialized and I can't figure out why. Reviewing some code, and my root class is marked serializable:

[Serializable]
public class MyClass

I have a default constructor that initializes 10-15 string members. There are about 50 public read/write string members in MyClass with get and set--no explicit serialization attributes are set on any of these. Serialization looks like this:

XmlSerializer x = new XmlSerializer(typeof(MyClass));
TextWriter twWriter = new StreamWriter(sFileName);
x.Serialize(twWriter, this);
twWriter.Close();

only a handful (20-30) of these members are actually seralized to my xml file. what am i missing or misunderstanding about the XmlSerializer class?

A: 

indeed, they are not serialized if they are null.

David
+2  A: 

You can force a null property to be serialized in the output by setting IsNullable to true on the XmlElement attribute.

public class Example
{
    [XmlElement(IsNullable=true)]
    public string Text { get; set; }
}

The Text property will now be serialized as <Text xsi:nil="true" />.

On a side note the [Serializable] attribute is not needed if you are only doing XML serialization.

João Angelo