Search code examples
c#xmlserializer

How to serialize List<T> in c# without the ArrayOf wrapper?


I'm attempting to serialize a List<T> of some custom classes with:

List<T> l = new List<T>();
...
XmlSerializer serializer = new XmlSerializer(l.GetType());
serializer.Serialize(writer, list);

And it outputs:

<ArrayOfT>
    <T>
        ...
    </T>
    <T>
        ...
    </T>
</ArrayOfT>

How do I get the same thing, but without the ArrayOfT elements, so it would look like:

<T>
    ...
</T>
<T>
    ...
</T>

I'm attempting to do this because it's happening in a wrapper class so my actual output is coming in the format of:

<PropertyName>
    <ArrayOfT>
        <T>
            ...
        </T>
        <T>
            ...
        </T>
    </ArrayOfT>
</PropertyName>

And the ArrayOfT element is redundant (logically it would have the same name as PropertyName.)


Solution

  • You could do this approach perhaps:

    XmlSerializer serializer = new XmlSerializer(l.GetType());
    foreach (T item in list)
    {
        serializer.Serialize(writer, item);
    }
    

    This way you are serializing the items but not the outer object.