Given a type such as:
public class FooList : List<Foo>
{
public string SomeMessage { get; set; }
}
How can I get the SomeMessage property to be serialized along with the collection without overriding serialization itself?
What I am getting is:
<FooList>
<Foo />
<Foo />
<Foo />
</FooList>
and what I want is:
<FooList>
<SomeMessage />
<Foo />
<Foo />
<Foo />
</FooList>
For whatever reason, (I think it is because the serialization being used for the generic list doesn’t see the new property) it isn’t being written out.
In case it matters, here is what I am using to serialize it.
FooList content = new FooList();
content.SomeMessage="this is a test";
//add foos
using (TextWriter writer = new StreamWriter("C:\\foos.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(FooList));
serializer.Serialize(writer, content);
}
When the
XmlSerializerserializes a collection, it only takes the items of the collection into account. Any extra property declared in the class is ignored. You will either have to implementIXmlSerializableto provide your own serialization logic, or change the design of your class.You could do something like that: