Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I configure the DataContractSerializer to not create optional (i.e. Nullable<> and List<>) elements in output XML?

I am using the new .NET 3.0 DataContractSerializer. I have both Nullable<> and List<> objects I am going to serialize. Example:

[DataContract(Namespace = "")]
class Test
{
    public static void Go()
    {
        Test test = new Test();

        var dcs = new DataContractSerializer(typeof(Test));
        dcs.WriteObject(new StreamWriter("test.xml").BaseStream, test);
    }

    [DataMember]
    public Nullable<int> NullableNumber = null;

    [DataMember]
    public int Number = 5;

    [DataMember]
    public List<int> Numbers = new List<int>();
}

When .NET serializes a null or an empty list, it puts in nil (for Nullable) and empty (for lists) elements into the XML. The above example generates:

<Test xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <NullableNumber i:nil="true"/>
  <Number>5</Number>
  <Numbers xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
</Test>

For reasons I don't have time to describe I would like to eliminate the superfluous NullableNumber and Numbers elements, like so:

<Test xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Number>5</Number>
</Test>

Indeed, the above file deserializes with the serializer just fine.

Thanks for your help!

like image 640
Eric Avatar asked Apr 01 '09 23:04

Eric


People also ask

How do you serialize an object in WCF?

This code constructs an instance of the DataContractSerializer that can be used only to serialize or deserialize instances of the Person class. DataContractSerializer dcs = new DataContractSerializer(typeof(Person)); // This can now be used to serialize/deserialize Person but not PurchaseOrder.

Which namespace is used in WCF for data serialisation?

DataContractSerializer as the Default By default WCF uses the DataContractSerializer class to serialize data types.

What is by serialization with respect to WCF?

The process forms a sequence of bytes into a logical object; this is called an encoding process. At runtime when WCF receives the logical message, it transforms them back into corresponding . Net objects. This process is called serialization.


1 Answers

Mark the field with

   [DataMember(EmitDefaultValue=false)]

That will work for at the least the nullable value type case. For the List case you may need to defer creation of the list until it is needed, or else null the member if it is empty before serialization.

like image 183
Darren Clark Avatar answered Oct 15 '22 15:10

Darren Clark