0

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.)

6
  • Use the [XmlElement("T")] attribute if l is a property in a class. Commented Jan 11, 2018 at 17:26
  • @TheLethalCoder I'm trying to completely remove the ArrayOfT element, not rename it, also l is not a property, it is a variable within an implementation of IXmlSerializable.WriteXml(XmlWriter writer) which is in the class which makes up the property. Commented Jan 11, 2018 at 17:35
  • Couldn't you just loop over the list? Commented Jan 11, 2018 at 17:41
  • @juharr Apparently so, I'm chalking this up to my unfamiliarity with the XmlSerializer, if you want to post this as an answer I'll accept it. Commented Jan 11, 2018 at 17:46
  • 1
    Possible duplicate of XML Serialization - Disable rendering root element of array Commented Jan 11, 2018 at 18:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is correct but while I voted it up I'm not marking it as accepted yet just because @juharr mentioned it first in a comment and I want to give him time to submit it as an answer, I'll check back tomorrow and if he hasn't posted it I'll accept this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.