Search code examples
c#xml-serializationdatacontractserializer

Data Contract Serializer - How to omit the outer element of a collection


How do I serialize a list without the outer element using the Data Contract Serializer? I am using .Net 3.5. I have a class that contains a list, amongst other things, that I wish to serialize without the outer element to be compliant with the pertinent XSD:

[DataContract(Name="MyClass")]
public class MyClass
{
...
[DataMember(Name="Parameters")]
public List<Parameter> Parameters;
...
}

[DataContract(Name="Parameter")]
public struct Parameter
{
    [DataMember(Name="ValueName")]string ValueName;
    [DataMember(Name="Value")]int Value;
    public Parameter(string ValueName, int Value)
    {
        this.ValueName = ValueName;
        this.Value = Value;            
    }
}

The above serializes as (assuming only one Parameter in the list):

<MyClass>
    <Parameters>
       <Parameter>
           <ValueName></ValueName>
           <Value></Value>
       </Parameter>
    </Parameters>
</MyClass>

I would like to serialize it as follows:

<MyClass> 
       <Parameter>
           <ValueName></ValueName>
           <Value></Value>
       </Parameter>
</MyClass>

Using the XmlSerializer I can do this by applying the [XmlElement] to the list:

[XmlElement ("Parameter")]
public List<Parameter> Parameters;

However I do not want to use the XmlSerializer because my class has a few properties that are not serialization friendly and I was hoping to deal with those using the [OnSerializing] family of attributes.

Thanks.


Solution

  • The DataContract serializer does not allow this degree of control over the resulted XML, you will have to use instead the XmlSerializer in order to achieve this.