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

CoryG
  • 2,429
  • 3
  • 25
  • 60
  • Use the `[XmlElement("T")]` attribute if `l` is a property in a class. – TheLethalCoder Jan 11 '18 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. – CoryG Jan 11 '18 at 17:35
  • Couldn't you just loop over the list? – juharr Jan 11 '18 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. – CoryG Jan 11 '18 at 17:46
  • 1
    Possible duplicate of [XML Serialization - Disable rendering root element of array](https://stackoverflow.com/questions/2006482/xml-serialization-disable-rendering-root-element-of-array) – ASpirin Jan 11 '18 at 18:53
  • When serializing the `List` as the root object you cannot eliminate the outer `` because a well-formed XML document must have one and only one [root elemnent](https://en.wikipedia.org/wiki/Root_element). When the `List` is a nested member in some containing type then [XML Serialization - Disable rendering root element of array](https://stackoverflow.com/questions/2006482/xml-serialization-disable-rendering-root-element-of-array) is the answer and this question is a duplicate. – dbc Jan 12 '18 at 05:48

1 Answers1

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.

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
  • 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. – CoryG Jan 11 '18 at 19:04