I've run into an issue with serializing an IEnumerable
with the XmlSerializer
. Since IEnumerable
represents a list of object
, XmlSerializer
doesn't know ahead of time what types it needs to serialize. But because it needs to know, it throws an InvalidOperationException
when it encounters a type other than object
.
The type Foo.Bar was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
The XmlIncludeAttribute
is intended to be applied to a method to indicate that the return value can be a certain type. However, IEnumerable
has no method that I could put the attribute on.
I tried applying them to GetEnumerator
:
public class Bar : IEnumerable
{
private List<object> list;
public Bar()
{
}
[XmlInclude(typeof(Bar))]
[XmlInclude(typeof(ChildBar))]
public IEnumerator GetEnumerator()
{
return list.GetEnumerator();
}
public void Add(Bar bar)
{
list.Add(bar);
}
public void Add(ChildBar childBar)
{
list.Add(childBar);
}
// used for deserialization
public void Add(object o)
{
if (o is Bar || o is ChildBar)
{
list.Add(o);
}
}
// more irrelevant stuff
}
public class ChildBar
{
public ChildBar()
{
}
// more irrelevant stuff
}
That didn't solve it, and I have no idea where else to use the attributes.
Where should I put them? Can I work around it without them? Can I avoid writing my own enumerator?