This is a bit of a long question, but I've made it as terse as possible, so please bear with me. It looks to me like a bug in the XmlSerializer
class but before I file it with Microsoft I'd like to see if there's anything I've missed, which is entirely possible.
I'm attempting to generate the following XML as a representative case, which is essentially a collection of collections, but where the outer collection has additional elements:
<Links>
<Name />
<Group>
<Link />
<Link />
</Group>
<Group>
<Link />
<Link />
</Group>
</Links>
The serialization classes are as follows:
public class Link { }
public class Links
{
public string Name { get; set; }
[XmlElement("Group")]
public Link[][] Groups { get; set; }
}
And a simple test program to run it is as follows:
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(Links));
var links = new Links { Name = "", Groups = new[] {
new[] { new Link(), new Link() },
new[] { new Link(), new Link() } } };
serializer.Serialize(Console.Out, links);
}
}
This employs the trick of using XmlElement
to remove the parent node of the collection, which should mean that no <Groups>
element is emitted, and for each object contained in the outer array (which will be of type Link[]
) a <Group>
element should be emitted. However, at runtime, this gives the following exception from the XmlSerializer
:
Unable to generate a temporary class (result=1). error CS0030: Cannot convert type 'Link[][]' to 'Link[]' error CS0029: Cannot implicitly convert type 'Link[]' to 'Link[][]'
My guess is that the serializer is for some reason attempting to flatten the collection, and thinks that the type contained in the outer array is Link
rather than Link[]
which causes the compilation failure of its serialization classes as the types don't match.
What do you think? Is this a bug? And is there a workaround to generate the XML I'm after using the XmlSerializer
?